简体   繁体   中英

Get the selected value of a dropdown list

I have the follwing code. I want to get the value of the selected value of the dropdownlist once the user changes it or to have the default value to be displayed by alert(). I need to use alert() from within the < body > of the html. Is that possible?

<html>
 <head>
 <title>Title</title>
 <script type="text/javascript" src="phonegap-1.4.1.js">
</script> <script type="text/javascript" src="JS/Util.js"></script>
 <script type="text/javascript" src="JS/Language.js"></script>
 <script type="text/javascript">
   function dropdown(){
  var drp = document.getElementById("numberlist");
 var optn = document.createElement("OPTION");
 optn.text="3";
 optn.value="3";
 drp.add(optn);
 }
    </script>
 </head>
  <body onload="dropdown();"> <div id="main3"></div>  <form><select id = "numberlist"><option>12</option><option>24</option><option>36</option></select>

Use the code:

selectElement.options[ selectElement.options.selectedIndex ];

to find the index that is selected.

So where you say var drp = document.getElementById("numberlist"); you can now find the value of the index by doing:

var value = drp.options[ drp.options.selectedIndex ].value;

Add the code into an onchange event so that whenever you change the selectedIndex of the element, you will be able to obtain it's value:

Here is a DEMO

add this function within script tag.

function pickvalue(id){
   var drp = document.getElementById(id);
   alert(drp.value);
}

and add function call like this.

<select id = "numberlist" onchange="pickvalue(this.id)">

Try this Following...Mark it as answer if it helps you

<html>  
<head>  
<title>Title</title>  
<script type="text/javascript" src="phonegap-1.4.1.js"> </script> <script         type="text/javascript" src="JS/Util.js"></script>  
<script type="text/javascript" src="JS/Language.js"></script> 
<script type="text/javascript">    
function dropdown()
{   
    var drp = document.getElementById("numberlist");  
    var optn = document.createElement("OPTION");  
    optn.text="3";  
    optn.value="3";  
    drp.add(optn);  
}  

</script>  
</head>   
<body onload="dropdown();"> 
<div id="main3">
</div>  
<form>
<select id="numberlist" onchange="show()">
<option>12</option>
<option>24</option>
<option>36</option>
</select> 
<script type="text/javascript">
    function show() {
        var e = document.getElementById('numberlist');
        var txt = e.options[e.selectedIndex].text;
        alert(txt);


    }   
</script>
</form>
</body>
</html>

Here is a JQuery method:

 $value = $("#numberlist option:selected").text();
 alert($value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM