Question

There is a select element that have options created dynamically. I want to post these options text-value pairs via ajax etc...

Is it possible to make them stringify as text-value pairs? Or any suggestions without stringifying text-value pairs. Thanks.

Was it helpful?

Solution

Use this if you don't have jQuery

function getSelectOptions(id){
    var select = document.getElementById('x');
    var obj = {};
    for(var i=0; i< select.options.length; i++){
        var option = select.options[i];
        obj[option.value] = option.innerHTML;
    }
    return obj;    
}
var opts = getSelectOptions('x');
console.log(opts, JSON.stringify(opts))

Demo: Fiddle

With jQuery

function getSelectOptions(id){
    var select = $('#' + id);
    var obj = {};
    $('option', select).each(function(i, v){
        var $this = $(this);
        obj[$this.val()] = $this.text();
    });
    return obj;    
}
var opts = getSelectOptions('x');
console.log(opts, JSON.stringify(opts))

Demo: Fiddle

OTHER TIPS

In GET request, you can send them in this form:

targetpage.php?option[key1]=value1&option[key2]=value2...

The server should understand this as key-value array. To get the option values, use the code Arun P Johny suggests.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top