select <select> item by value

后端 未结 6 1425
时光取名叫无心
时光取名叫无心 2020-12-09 19:19

i have


         


        
6条回答
  •  萌比男神i
    2020-12-09 19:37

    If you can, with ES6...

    function setOption(selectElement, value) {
        return [...selectElement.options].some((option, index) => {
            if (option.value == value) {
                selectElement.selectedIndex = index;
                return true;
            }
        });
    }
    

    ...otherwise...

    function setOption(selectElement, value) {
        var options = selectElement.options;
        for (var i = 0, optionsLength = options.length; i < optionsLength; i++) {
            if (options[i].value == value) {
                selectElement.selectedIndex = i;
                return true;
            }
        }
        return false;
    }
    
    setOption(document.getElementById('my-select'), 'b');
    

    See it!

    If it returns false, then the value could not be found :)

提交回复
热议问题