javascript - 将元素属性放入输入值

标签 javascript jquery html

我的网站上有一个简单的联系表单,它是使用在线生成器创建的(因此我无法更改 html 代码并将 id 添加到元素)。这是我的表单示例:

https://jsfiddle.net/kerm131/w6oa7uhe/30/

        $("[data-type='phone'] .input .form-control").intlTelInput({

          allowDropdown: true,
          autoPlaceholder: "aggressive",
          initialCountry: "auto",
          geoIpLookup: function(success, failure) {
            $.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
              var countryCode = (resp && resp.country) ? resp.country : "";
              success(countryCode);
            });
          },
        });
        let country = document.querySelector('selected-flag[title]');
        $("[data-type='hidden'] .input .form-control").val($(country));
        
.field {
  padding: 10px 0;
}

.form-control {
  padding: 10px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/14.0.6/css/intlTelInput.css">
<div class="fields">
  <div class="field" data-type="name" style="width: 247px;">
    <div class="input"><input class="form-control text" type="text" data-placeholder="true" value="Wie sollen wir Sie ansprechen?" style="border-radius: 15px;"></div>
  </div>
  <div class="field" data-type="phone" style="width: 247px;">
    <div class="input"><input class="form-control text" type="text" data-placeholder="true" style="border-radius: 15px;"></div>
  </div>
  <div class="field" data-type="email" style="width: 247px;">
    <div class="input"><input class="form-control text" type="text" data-placeholder="true" value="E-Mail Adresse *" style="border-radius: 15px;"></div>
  </div>
  <div class="field" data-type="hidden" style="width: 247px;">
    <div class="input"><input class="form-control" type="text" style="border-radius: 15px;" value="hidden content"></div>
  </div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/14.0.6/js/intlTelInput-jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/14.0.6/js/utils.js"></script>

在电话号码字段中有 int-tel-input jQuery 插件,它使用用户 ip 设置国家拨号代码。我想将此信息复制到隐藏字段。或者更准确地说,从具有类 .selected-flag 的元素的属性“标题”中获取数据,并填写此信息“隐藏”字段。

不幸的是,我的 JS 和 jQuery 技能很差,所以我不知道如何让它工作。你可以在JS代码栏看到我的尝试。

请给我一个提示或解决方案来解决我的问题。

最佳答案

因为我完全忘记了 DOMSubtreeModified 事件已被弃用——而且因为,如 Smollet777准确评论,DOMSubtreeModified 方法在更改标志时不起作用 - 建议使用以下方法而不是版本:

// caching the elements ('target' and 'recipient') for later use:
let target = document.querySelector('.selected-flag'),
    recipient = document.querySelector('[data-type=hidden] input.form-control'),

// setting the options for the MutationObserver, these are the
// mutation-types we're looking for:
    options = {
      'attributes' : true
    },

// the MutationObserver callback function:
    observationHandler = function(mutations, observer){

      // for each mutation of the list of mutations:
      for (let mutation of mutations) {

        // we update the value property of the recipient Node,
        // setting that value to the 'title' property-value
        // from the 'target' Node:
        recipient.value = target.title;
      }
    },

 // initialising a new MutationObserver, passing in the
 // callback function:
    observer = new MutationObserver(observationHandler);

 // using the observer.observe() method to observe the
 // 'target' Node using the options defined earlier:
    observer.observe(target, options);

$("[data-type='phone'] .input .form-control").intlTelInput({

  allowDropdown: true,
  autoPlaceholder: "aggressive",
  initialCountry: "auto",
  geoIpLookup: function(success, failure) {
    $.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
      var countryCode = (resp && resp.country) ? resp.country : "";
      success(countryCode);
    });
  },
});

let target = document.querySelector('.selected-flag'),
  recipient = document.querySelector('[data-type=hidden] input.form-control'),
  options = {
    'attributes': true
  },
  observationHandler = function(mutations, observer) {
    for (let mutation of mutations) {
      recipient.value = target.title;
    }
  },
  observer = new MutationObserver(observationHandler);

observer.observe(target, options);
.field {
  padding: 10px 0;
}

.form-control {
  padding: 10px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/14.0.6/css/intlTelInput.css">
<div class="fields">
  <div class="field" data-type="name" style="width: 247px;">
    <div class="input"><input class="form-control text" type="text" data-placeholder="true" value="Wie sollen wir Sie ansprechen?" style="border-radius: 15px;"></div>
  </div>
  <div class="field" data-type="phone" style="width: 247px;">
    <div class="input"><input class="form-control text" type="text" data-placeholder="true" style="border-radius: 15px;"></div>
  </div>
  <div class="field" data-type="email" style="width: 247px;">
    <div class="input"><input class="form-control text" type="text" data-placeholder="true" value="E-Mail Adresse *" style="border-radius: 15px;"></div>
  </div>
  <div class="field" data-type="hidden" style="width: 247px;">
    <div class="input"><input class="form-control" type="text" style="border-radius: 15px;" value="hidden content"></div>
  </div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/14.0.6/js/intlTelInput-jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/14.0.6/js/utils.js"></script>

JS Fiddle demo .

针对评论中提出的问题,该解决方案仅适用于页面上多个相似表单中的第一个,修改如下以适用于多个相似表单:

// cache all relevant elements, using document.querySelectorAll():
let targets = document.querySelectorAll('.selected-flag'),
  options = {
    'attributes': true
  },
  observationHandler = function(mutations, observer) {
    for (let mutation of mutations) {

      // here we cache the current target (the element to which
      // the observationHandler is bound):
      let target = mutation.target,

      // we find the 'recipient' node, the element you wish
      // to update; here we navigate from the 'target' to the
      // closest ancestor element matching the supplied CSS
      // selector, and from there we look for the first (if any)
      // nodes matching the CSS selector passed to
      // document.querySelector():
            recipient = target.closest('div.fields').querySelector('[data-type="hidden"] input');

      // here we update the value of the 'recipient' node:
          recipient.value = target.title;
    }
  },
  observer = new MutationObserver(observationHandler);

  // iterating over the NodeList of elements:
  targets.forEach(

    // here we bind the mutation observer to each
    // of the matching elements from the NodeList:
    (target) => observer.observe(target, options)
  );

JS Fiddle demo .

不幸的是,由于 Stack Overflow 答案的字符限制——以及提供的演示的长度——我无法在此处发布工作片段,但链接的 JS Fiddle 演示确实包含完整的工作代码。

引用资料:

关于javascript - 将元素属性放入输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53582352/

相关文章:

php - jQuery 手机 : How to correctly submit form data

javascript - 拖放 firefox ghost 图像位置

javascript - 使用 jQuery 在祖先和后代之间插入元素

jquery - 围绕 3 个连续 <td> 的单个旋转虚线边框

javascript - 在 jquery Mobile 中获取表单 ID 'pageshow'

javascript - Node.js,OpenCV 尝试使用 toBuffer() 函数将矩阵转换为缓冲区

javascript - 当用户尝试删除 indexedDB 数据库时,有没有办法执行函数?

javascript - Jquery 键/值 = 未定义

javascript - Ajax成功函数

javascript - 引用错误: Can't find variable: clicked in node. js