I have a select list (sample below). I want to store this select list (text and value) in a JSON object or Array object. So that i can later go thru it using .each function. I want to then show/hide the records in the select option list based on user input. all code is ready and working except that I am not able to figure how to store a select option list with all its text and value pairs into an either Array or JSON object and subsequently able to walk thru it based on text.
thank you.
<select id="mySelect" multiple="multiple">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
You can try this fiddle:
HTML
<select id="mySelect" multiple="multiple">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
JAVASCRIPT
var options = {};
$('#mySelect option').each(function(){
options[$(this).text()] = $(this).val();
});
console.log(options);
//or the other way round
var options2 = {};
$('#mySelect option').each(function(){
options2[$(this).val()] = $(this).text();
});
console.log(options2);
Console Log Output:
Object
First: "1"
Fourth: "4"
Second: "2"
Third: "3"
__proto__: Object
fiddle.jshell.net:36
Object
1: "First"
2: "Second"
3: "Third"
4: "Fourth"
__proto__: Object
My answer is very similar to @topek's but I'm using object to store array elements so it may be useful. You can inspect working example here.
HTML:
<select id="mySelect" multiple="multiple">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
Javascript:
var options = [];
$('#mySelect option').each(function() {
options.push({ "id" : this.value, "text" : this.textContent });
});