set option “selected” attribute from dynamic created option

后端 未结 17 1700
时光说笑
时光说笑 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:45

    Realize this is an old question, but with the newer version of JQuery you can now do the following:

    $("option[val=ID]").prop("selected",true);
    

    This accomplishes the same thing as Box9's selected answer in one line.

    0 讨论(0)
  • 2020-11-30 20:51

    You could search all the option values until it finds the correct one.

    var defaultVal = "Country";
    $("#select").find("option").each(function () {
    
        if ($(this).val() == defaultVal) {
    
            $(this).prop("selected", "selected");
        }
    });
    
    0 讨论(0)
  • 2020-11-30 20:51

    To set value in JavaScript using set attribute , for selected option tag

    var newvalue = 10;
    var x = document.getElementById("optionid").selectedIndex;
        document.getElementById("optionid")[x].setAttribute('value', newvalue);
    
    0 讨论(0)
  • 2020-11-30 20:52

    The ideas on this page were helpful, yet as ever my scenario was different. So, in modal bootstrap / express node js / aws beanstalk, this worked for me:

    var modal = $(this);
    modal.find(".modal-body select#cJourney").val(vcJourney).attr("selected","selected");
    

    Where my select ID = "cJourney" and the drop down value was stored in variable: vcJourney

    0 讨论(0)
  • 2020-11-30 20:55

    This should work.

    $("#country [value='ID']").attr("selected","selected");
    

    If you have function calls bound to the element just follow it with something like

    $("#country").change();
    
    0 讨论(0)
  • 2020-11-30 20:56

    Good question. You will need to modify the HTML itself rather than rely on DOM properties.

    var opt = $("option[val=ID]"),
        html = $("<div>").append(opt.clone()).html();
    html = html.replace(/\>/, ' selected="selected">');
    opt.replaceWith(html);
    

    The code grabs the option element for Indonesia, clones it and puts it into a new div (not in the document) to retrieve the full HTML string: <option value="ID">Indonesia</option>.

    It then does a string replace to add the attribute selected="selected" as a string, before replacing the original option with this new one.

    I tested it on IE7. See it with the reset button working properly here: http://jsfiddle.net/XmW49/

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