当前位置: 动力学知识库 > 问答 > 编程问答 >

Read HTML array using javascript or jQuery

问题描述:

I have array element in HTML

<input type="checkbox" value="Value1" name="model[settings][]">

<input type="checkbox" value="Value2" name="model[settings][]">

<input type="checkbox" value="Value3" name="model[settings][]">

I am reading all the HTML input, iterating it and building a hash in the javascript. But this will read the array element and only pick the last model[settings][] element.

var inputs = jQuery(" :input", "#elementID");

Is there a way in jQuery or JavaScript to read and build an array variable in javascript which then can be passed to controller ?

Thank You

网友答案:

If I understand you correctly, you are trying to iterate through all your input elements to get their value and store that as a JS object, correct? If that's the case, I would add a unique ID to all my inputs, and then create an object with the structure { id : value }:

function getInputObject(sel) {
  sel = $(sel);
  var out = {};
  sel.each(function() {
    out[$(this).attr("id")] = $(this).val();
  });
  return out;
}
$(document).ready(function() {
  console.log( getInputObject("input") );
});
input {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="input1" value="value input 1" type="text" />
<input id="input2" value="value input 2" type="text" />
<input id="input3" value="value input 3" type="text" />
分享给朋友:
您可能感兴趣的文章:
随机阅读: