×

JavaScript设置选择框元素的值

作者:Terry2019.12.30来源:Web前端之家浏览:6711评论:0
关键词:js

在javascript中,selectedIndex属性可用于设置选择框(select)元素的值;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>

示例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”; 它将取消选择所选框的所有元素。

示例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>

大家预览看下吧。

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/jsu283409283409.html

网友评论文明上网理性发言 已有0人参与

发表评论: