如何使用jQuery在Array中获取具有不同data-id的多输入字段的值?

时间:2017-06-19 21:23:50

标签: javascript jquery backbone.js

我的表单有多个输入字段,使用骨干我用data-id生成多个输入字段。每次data-id的顺序都不同。

现在,我需要获取用户创建和填充的所有输入字段的值。 (将在点击事件中填充值,用户可以创建多个输入字段。)

<div class="Title" data-id="title_1">
  <label>Additional Title</label>
  <input type="text">
</div>

<div class="Title" data-id="title_2">
  <label>Additional Title</label>
  <input type="text">
</div>

<div class="Title" data-id="title_3">
  <label>Additional Title</label>
  <input type="text">
</div>

<div class="Title" data-id="title_4">
  <label>Additional Title</label>
  <input type="text">
</div>

<div class="Title" data-id="title_5">
  <label>Additional Title</label>
  <input type="text">
</div>

2 个答案:

答案 0 :(得分:2)

为所有文本框提供相同的类,以便您可以轻松访问用户生成的文本框

这是你的HTML

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

<div class="Title" data-id="title_1">
  <label>Additional Title</label>
  <input class="textfield" type="text" value="val 1">
</div>

<div class="Title" data-id="title_2">
  <label>Additional Title</label>
  <input class="textfield"  type="text" value="val 2">
</div>

<div class="Title" data-id="title_3">
  <label>Additional Title</label>
  <input type="text" class="textfield" value="val 3">
</div>

<div class="Title" data-id="title_4">
  <label>Additional Title</label>
  <input type="text" class="textfield" value="val 4">
</div>

<div class="Title" data-id="title_5">
  <label>Additional Title</label>
  <input type="text" class="textfield" value="val 5">
</div>

这是你的jquery

$( ".textfield" ).each(function( index ) {
  debugger;
  console.log( $(this).closest('div').attr('data-id'));
  console.log( index + ": " + $( this ).val() );
});

答案 1 :(得分:-1)

https://jsfiddle.net/L3xyL4oe/

//bind selector methods to easy to use functions
let $$ = document.querySelectorAll.bind(document);
let $ = document.querySelector.bind(document);

//setup function to quickly change dom list to an array
let toArray = (domList) => [].slice.call(domList);

//when button is clicked
$("button").addEventListener('click', () => {
  //get all the inputs into an array
  let inputs = toArray($$(".Title[data-id^='title'] > input"));

  //iterate through the array
  for (let input of inputs) {
  //for each input with a value, alert the value
    if (input.value) alert(input.value);
  }
});