如何使用JavaScript设置选择框元素的值?

在javascript中,selectedIndex属性可用于设置选择框(select)元素的值;selectedIndex属性在下拉列表中设置或返回选定值的索引。下面本篇文章就来给大家介绍一下javascript的selectedIndex属性,希望对大家有所帮助。

javascript的selectedIndex属性

selectedIndex属性可设置或返回下拉列表中被选选项的索引号。

语法:

设置selectedIndex 属性:

selectObject.selectedIndex = number

返回selectedIndex 属性:

selectObject.selectedIndex

注意:整数(Integer number)用于值位置的索引。

示例1:选择索引号

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
   </head>  
   <body>
   <h2>使用selectedIndex属性</h2>
    <select id="mySelect"> 
        <option>football</option> 
        <option>Basketball</option> 
        <option>Hockey</option> 
        <option>Swiming</option> 
    </select> 
  
    <p>单击按钮,以选择索引为“2”的选项元素。</p> 
  
    <button onclick="myFunction()">选择</button> 
  
    <script> 
        function myFunction() { 
            document.getElementById("mySelect").selectedIndex = "2"; 
        } 
    </script> 
  
</body> 
  
</html>

效果图:

1.gif

示例2:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
   </head>  
   <body>
   <h2>使用selectedIndex属性</h2>
    <select id="mySelect"> 
        <option>football</option> 
        <option>Basketball</option> 
        <option>Hockey</option> 
        <option>Swiming</option> 
    </select> 
  
    <p>单击按钮,取消选择选项。</p> 
  
    <button onclick="myFunction()">选择</button> 
  
    <script> 
        function myFunction() { 
            document.getElementById( 
              "mySelect").selectedIndex = "-1"; 
        } 
    </script> 
  
</body> 
  
</html>

上例中,选择框设置selectedIndex =“ - 1”; 它将取消选择所选框的所有元素。

效果图:

2.gif

示例3:如果未选择任何元素,则此属性返回-1。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
   </head>  
   <body>
   <h2>使用selectedIndex属性</h2>
    <select id="mySelect"> 
        <option>football</option> 
        <option>Basketball</option> 
        <option>Hockey</option> 
        <option>Swiming</option> 
    </select> 
  
    <p>单击按钮,取消选择选项。</p> 
  
    <button onclick="myFunction()">选择</button> 
  
    <script> 
         //Here we delselect all the options  
        function myFunction() { 
            document.getElementById( 
              "mySelect").selectedIndex = "-1"; 
        } 
        function yourFunction() { 
            var x = document.getElementById( 
              "mySelect").selectedIndex; 
            
            document.getElementById( 
              "demo").innerHTML = x; 
        }
    </script> 
    <button type="button" onclick="yourFunction()"> 显示索引</button> 
    <p id="demo"></p>
  
</body> 
  
</html>

输出:

3.gif

以上就是如何使用JavaScript设置选择框元素的值?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » JavaScript 答疑