How to create json by JavaScript for loop?
I have array of select tag.
<select id='uniqueID' name="status">
<option value="1">Present</option>
<option value="2">Absent</option>
</select>
and I want to create a json object having two fields 'uniqueIDofSelect and optionValue' in JavaScript.
I use getElementsByName("status") and I iterate on it.
EDIT
I need out put like
[{"selectID":2,"OptionValue":"2"},
{"selectID":4,"optionvalue":"1"}]
and so on...
From what I understand of your request, this should work:
<script>
// var status = document.getElementsByID("uniqueID"); // this works too
var status = document.getElementsByName("status")[0];
var jsonArr = [];
for (var i = 0; i < status.options.length; i++) {
jsonArr.push({
id: status.options[i].text,
optionValue: status.options[i].value
});
}
</script>
var sels = //Here is your array of SELECTs
var json = { };
for(var i = 0, l = sels.length; i < l; i++) {
json[sels[i].id] = sels[i].value;
}