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...
If I want to create JavaScript Object from string generated by for loop then I would JSON to Object approach. I would generate JSON string by iterating for loop and then use any popular JavaScript Framework to evaluate JSON to Object.
I have used Prototype JavaScript Framework. I have two array with keys and values. I iterate through for loop and generate valid JSON string. I use evalJSON() function to convert JSON string to JavaScript object.
Here is example code. Tryout on your FireBug Console
Your question is pretty hard to decode, but I'll try taking a stab at it.
You say:
And then you say:
Well, this example output doesn't have the field named
uniqueIDofSelect
, it only hasoptionValue
.Anyway, you are asking for array of objects...
Then in the comment to michaels answer you say:
So you don't want an array of objects?
What do you want then?
Please make up your mind.
From what I understand of your request, this should work:
If you want a single JavaScript object such as the following:
(where option 2, "Absent", is the current selection) then the following code should produce it:
If you want an array of all such objects (not just the selected one), use michael's code but swap out
status.options[i].text
forstatus.id
.If you want a string that contains a JSON representation of the selected object, use this instead: