Reputation: 99
I need options' value list in an array or JSON. I have used following code.
var compArray=[];
jQuery("#myCombo option").each(function(){
compArray.push(jQuery(this).val());
});
But i dont want to iterate the options in a loop because my options list can grow. I have used as
JSON.stringify(document.getElementById("myCombo").options)
But on stringify it shows empty JSON objects, though I can get value from
document.getElementById("myCombo").options[0].value
I have to pass these value in request parameter to server and I do not want to go through the looping. Please suggest the optimized solution.
Upvotes: 3
Views: 1006
Reputation: 45121
You can use custom serializer like this:
var options = Array.prototype.slice.call(document.getElementById("sel").options),
str = JSON.stringify(options, function(key, value){
if(key === ""){
return value;
}
if(!isNaN(parseInt(key))) {
return value.value;
}
};
Or use iteration without creating jQuery instance for every option
var options = Array.prototype.slice.call(document.getElementById("sel").options),
str = JSON.stringify(options.map(function(item){return item.value;}));
Check this perf test: http://jsperf.com/get-options
Upvotes: 1
Reputation: 6003
But i dont want to iterate the options in a loop because my options list can grow.
This does not have anything to do with the combo.
Whenever you add/delete a option
to the combo, just call a function, which will subsequently add/delete that option
from your array.
function addDeleteListInArray( oVal, addDelete ) {
if( addDelete ) {
// add to array
compArray.push( oVal );
} else {
// delete from array
for( var i=0; i< compArray.length; i++ ) {
if( compArray[ i ] == oVal ) {
compArray.splice( i, 1 );
break;
}
}
}
}
Hope this helps.
Upvotes: 0