Search code examples
javascriptdomstringify

How to post all options in a select element with stringify the text and values?


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.


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