When we use the drop-down list box select, we need to trigger an event for the selected
If we want to get all the values of select, we can use a for loop to achieve it. The code is as follows:
var vi = document.all['list'].length; for(var i=0;i<vi;i++){ document.form2.list(i).value; //form2是<form>的名称 }
js方法: <select id="pid" onchange="gradeChange()"> <option grade="1" value="a">选项一</a> <option grade="2" value="b">选项二</a> </select> <script type="text/JavaScript"> function gradeChange(){ var objS = document.getElementById("pid"); var grade = objS.options[objS.selectedIndex].grade; alert(grade); } </script> jq方法: <select name="myselect" id="myselect"> <option value="opt1">选项1</option> <option value="opt2">选项2</option> <option value="opt3">选项3</option> </select> $("#myselect").change(function(){ var opt=$("#myselect").val(); ... });
Javascript gets the selected value of the select drop-down box
Now there is a drop-down box with id=test, how to get the selected value?
Use the native javascript method and the jquery method respectively
<select id="test" name=""> <option value="1">text1</option> <option value="2">text2</option> </select>
1: The native javascript method
1: Get the select object: var myselect=document.getElementById("test");
2: Get the index of the selected item: var index=myselect.selectedIndex; // selectedIndex represents the index of the selected item
3: Get the value of the selected item options: myselect.options[index] .value;
4: Get the text of the selected options: myselect.options[index].text;
2: jquery method (provided that the jquery library has been loaded)
1:var options=$ ("#test option:selected"); //Get the selected item
2:console.log(options.val()); //Get the value of the selected item
3:console.log(options .text()); //Get the text of the selected item
Related recommendations:
How to deal with the option overlay of select
javascript deletes all option code sharing in select
How to set the default selection for the Select option in Html
The above is the detailed content of Detailed explanation of the trigger event when the specified option is selected in select. For more information, please follow other related articles on the PHP Chinese website!