Selecting an option element from a dropdown by its text value

前端 未结 4 948
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-05 06:35

Given an HTML form element like:


                        
    
提交评论

  • 2021-01-05 07:07

    If you want to get an option by its innertext and not by the value you can do this:

    function go(){
        var dropdown = document.getElementById('mydropdown');
        var textSelected = 'Spam';
    
        for(var i=0, max=dropdown.children.length; i<max; i++) {
            if(textSelected == dropdown.children[i].innerHTML){
                alert(textSelected);
                return;
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-05 07:15

    I'd use the selectedIndex or a loop to select the option by text, the code below doesn't work.

    document.getElementById("mydropdown").text = 'Eggs';
    
    0 讨论(0)
  • 2021-01-05 07:23

    Older IE does not handle options of a select as child nodes, but all browsers implement the text property of a select's option collection.

    function selectbytext(sel, txt){
        if(typeof sel== 'string'){
            sel= document.getELementById(sel) || document.getELementsByName(sel)[0];
        }
        var opts= sel.options;
        for(var i= 0, L= opts.length; i<L; i++){
            if(opts[i].text== txt){
                sel.selectedIndex= i;
                break;
            }
        }
        return i;
    }
    
    0 讨论(0)
  • 提交回复
    热议问题