set option “selected” attribute from dynamic created option

后端 未结 17 1701
时光说笑
时光说笑 2020-11-30 20:01

I have a dynamically created select option using a javascript function. the select object is


<         


        
相关标签:
17条回答
  • 2020-11-30 20:56
    select = document.getElementById('selectId');
    var opt = document.createElement('option');
        opt.value = 'value';
        opt.innerHTML = 'name';
        opt.selected = true;
        select.appendChild(opt);
    
    0 讨论(0)
  • 2020-11-30 20:58
    // Get <select> object
    var sel = $('country');
    
    // Loop through and look for value match, then break
    for(i=0;i<sel.length;i++) { if(sel.value=="ID") { break; } }
    
    // Select index 
    sel.options.selectedIndex = i;
    

    Begitu loh.

    0 讨论(0)
  • 2020-11-30 21:00

    To set the input option at run time try setting the 'checked' value. (even if it isn't a checkbox)

    elem.checked=true;
    

    Where elem is a reference to the option to be selected.

    So for the above issue:

    var country = document.getElementById("country");
    country.options[country.options.selectedIndex].checked=true;
    

    This works for me, even when the options are not wrapped in a .

    If all of the tags share the same name, they should uncheck when the new one is checked.

    0 讨论(0)
  • 2020-11-30 21:02

    This works in FF, IE9

    var x = document.getElementById("country").children[2];
    x.setAttribute("selected", "selected");
    
    0 讨论(0)
  • 2020-11-30 21:03

    I was trying something like this using the $(...).val() function, but the function did not exist. It turns out that you can manually set the value the same way you do it for an <input>:

    // Set value to Indonesia ("ID"):
    $('#country').value = 'ID'
    

    ...and it get's automatically updated in the select. Works on Firefox at least; you might want to try it out in the others.

    0 讨论(0)
提交回复
热议问题