简体   繁体   中英

How to get the correct selected value in Select HTML from javascript?

I get users from mysql query. I show this users into table and add a HTML into php file to all users to change a value:

 ...
 do {
    echo "<td > <a>".$row["username"]."</a> </td> \n";  
    echo "<td > <a>".$row["name"]."</a> </td> \n";
    echo "<td > <select id='sel'> <option value='admin'>Admin</option> <option value='user'>User</option> </select> </td> \n";   
 } while ($row = mysql_fetch_array($result)); 
        echo "</tbody></table> \n";
 ... 

How can I get the option selected??

I'm trying get this in javascript but always get the same first value, independet value selected.

function myFunction() {
   var e = document.getElementById("sel");
   var strUser = e.options[e.selectedIndex].value;
}

Thanks!

Use the jquery .change function.

Fiddle :- https://jsfiddle.net/a2abaL44/1/

<script type="text/javascript">
$("#sel").change(function(){
    var selectVal = $(this).val();
})
</script>

https://api.jquery.com/change/

Because your loop will be executed multiple times (once for each user in the database), you will have many <select> elements with the same ID. You cannot have the same ID given to many different elements, and this is why your JavaScript is only returning the value of the first <select> .

If you tell me what you are needing the selected value for, I can update the answer further.

Your code is fine, Change your select to <select id="sel" onchange="myFunction();">

<script type="text/javascript">
function myFunction() {
   var e = document.getElementById("sel");
   var strUser = e.options[e.selectedIndex].value;
   alert(strUser);
}
</script>

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