简体   繁体   中英

How to set the value of a PHP variable to a selected value from a select box as it is selected?

I want the user to select an option from a select box. Then as the user clicks the option my variable sets itself as the selected value.

Is there a way of doing this without doing it on page load or using a button. I want it to change when the user selects an option.

I have tried using this

<script>
var e = document.getElementById("ADDITIONALINFO");
var option1 = e.options[e.selectedIndex].text;
</script>

The variable remains empty. The name and id of my select box is ADDITIONALINFO

If anyone can help I would really appreciate it!

You are doing it right, but you need to run your snippet when users change the selected options, in the onchange event:

var sel = document.getElementById("ADDITIONALINFO");

sel.onchange = function()
{
    var option1 = sel.options[sel.selectedIndex].text;
    alert(option1);
};

Fiddle , or in case you prefer jQuery .

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