100

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...

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
Vikas
  • 24,082
  • 37
  • 117
  • 159
  • I assume that optionValue should be the 'value' attribute of each 'option' element: 1, 2, etc. But what is the ID? Is it the text? "Present", "Absent", etc.? – system PAUSE May 28 '09 at 13:56
  • Okay, so if ID is the uniqueID of the select, then there can be only one optionValue, right? I suppose you want the current selection, and not an array of all the selections? – system PAUSE May 28 '09 at 14:18

5 Answers5

183

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>
donohoe
  • 13,867
  • 4
  • 37
  • 59
  • 43
    JSON is an object and not an array. – Gumbo May 28 '09 at 14:31
  • It creates json object array. but I need only one json object. – Vikas May 29 '09 at 08:36
  • 1
    Don't you have to declare array like var jsonObj = new Array(); cuz your example didn't work for me. When I change to new Array(), then it works. – Meow Apr 08 '11 at 04:30
  • 18
    `var jsonArr = [];` creates a new Array. `var jsonObj = {};` creates a new Object – b_dubb Apr 24 '12 at 15:26
  • So, dumb question, I know the difference between an array of objects and an object that contains an array of objects (pretty much, the difference between `jsonArr = []` and `jsonObj = {}` in this post). I have, maybe too often, and perhaps even erroneously, referred to an object that contains an array of objects that each hold (possibly different) name/value pairs as a "JSON object". Being familiar with simple JSON syntax (like what you would have in an actual `.json` file), I know that syntactically this is different. So, would you refer to just the array of objects as JSON, as well? – VoidKing Oct 15 '13 at 21:27
  • @VoidKing Not a dumb question. I would too ('refer to just the array of objects as JSON'). I may be wrong, but JSON is just a format. It is a text format that is completely language independent. – donohoe Dec 17 '13 at 22:07
  • @b_dubb By combining both of them you get Objects Array :D `[{}]` – Kyle Mar 24 '16 at 11:55
45
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;
}
Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
8

If you want a single JavaScript object such as the following:

{ uniqueIDofSelect: "uniqueID", optionValue: "2" }

(where option 2, "Absent", is the current selection) then the following code should produce it:

  var jsObj = null;
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsObj = { uniqueIDofSelect: status.id, optionValue: options[i].value };
        break;
     }
  }

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 for status.id.

If you want a string that contains a JSON representation of the selected object, use this instead:

  var jsonStr = "";
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsonStr = '{ '
                  + '"uniqueIDofSelect" : '
                  + '"' + status.id + '"'
                  + ", "
                  + '"optionValue" : '
                  + '"'+ options[i].value + '"'
                  + ' }';
        break;
     }
  }
Community
  • 1
  • 1
system PAUSE
  • 37,082
  • 20
  • 62
  • 59
4

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

var key = ["color", "size", "fabric"];
var value = ["Black", "XL", "Cotton"];

var json = "{ ";
for(var i = 0; i < key.length; i++) {
    (i + 1) == key.length ? json += "\"" + key[i] + "\" : \"" + value[i] + "\"" : json += "\"" + key[i] + "\" : \"" + value[i] + "\",";
}
json += " }";
var obj = json.evalJSON(true);
console.log(obj);
Gaurang Jadia
  • 1,516
  • 15
  • 18
0

Your question is pretty hard to decode, but I'll try taking a stab at it.

You say:

I want to create a json object having two fields uniqueIDofSelect and optionValue in javascript.

And then you say:

I need output like

[{"selectID":2,"optionValue":"2"},
{"selectID":4,"optionvalue":"1"}]

Well, this example output doesn't have the field named uniqueIDofSelect, it only has optionValue.

Anyway, you are asking for array of objects...

Then in the comment to michaels answer you say:

It creates json object array. but I need only one json object.

So you don't want an array of objects?

What do you want then?

Please make up your mind.

Rene Saarsoo
  • 13,580
  • 8
  • 57
  • 85
  • First thing: sorry that uniqueIDofSelect == selectID (Id of select element, I can keep my record's id as select element id (for record update perpose). I'll also have number of select element generated by foreach loop. Actually this loop is which we are using in asp.net MVC for displaying Enumerable objects. 2) You are right, My mistake that I was amusing that whole output is one json object. But it is actualy array of object. And so michael's answer is perfect. Thanks for Pointing out. – Vikas May 30 '09 at 10:54