How to select a value in dropdown javascript?

后端 未结 10 686
星月不相逢
星月不相逢 2020-11-27 03:17

i have a drop down like this


                        
    
提交评论

  • 2020-11-27 03:34

    Using Javascript:

    document.getElementById('drpSelectSourceLibrary').value = 'Seven';
    

    Using Jquery:

    $('select').prop('selectedIndex', 3); // This will select the 4th option from the dropdown list
    
    0 讨论(0)
  • 2020-11-27 03:36
    function setSelectedIndex(s, v) {
        for ( var i = 0; i < s.options.length; i++ ) {
            if ( s.options[i].value == v ) {
                s.options[i].selected = true;
                return;
            }
        }
    }
    

    Where s is the dropdown and v is the value

    0 讨论(0)
  • 2020-11-27 03:41

    easiest way is to just use this

    document.getElementById("mySelect").value = "banana";
    

    myselect is name of your dropdown banana is just one of items in your dropdown list

    0 讨论(0)
  • 2020-11-27 03:41

    The simplest possible solution if you know the value

    document.querySelector('option[value=" + value +"]').selected = true
    
    0 讨论(0)
  • 2020-11-27 03:42

    I realize that this is an old question, but I'll post the solution for my use case, in case others run into the same situation I did when implementing James Hill's answer (above).

    I found this question while trying to solve the same issue. James' answer got me 90% there. However, for my use case, selecting the item from the dropdown also triggered an action on the page from dropdown's onchange event. James' code as written did not trigger this event (at least in Firefox, which I was testing in). As a result, I made the following minor change:

    function setSelectedValue(object, value) {
        for (var i = 0; i < object.options.length; i++) {
            if (object.options[i].text === value) {
                object.options[i].selected = true;
                object.onchange();
                return;
            }
        }
    
        // Throw exception if option `value` not found.
        var tag = object.nodeName;
        var str = "Option '" + value + "' not found";
    
        if (object.id != '') {
            str = str + " in //" + object.nodeName.toLowerCase()
                  + "[@id='" + object.id + "']."
        }
    
        else if (object.name != '') {
            str = str + " in //" + object.nodeName.toLowerCase()
                  + "[@name='" + object.name + "']."
        }
    
        else {
            str += "."
        }
    
        throw str;
    }
    

    Note the object.onchange() call, which I added to the original solution. This calls the handler to make certain that the action on the page occurs.

    Edit

    Added code to throw an exception if option value is not found; this is needed for my use case.

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