Skip to content Skip to sidebar Skip to footer

How Do You Pass A Value To A Hidden Form Field When A Certain Option Is Selected?

I am new to javascript and cannot find an easy-to-understand answer. I would like a certain value to get passed to a hidden field when a user selects a certain option from the sel

Solution 1:

To keep this simple you could assign ids to the <select> and hidden <input> and listen to the change event via onchange() on the <select> with a function call.

And based on the selected item, change the value of hidden input.

NOTE: To test the snippet out I have removed the type="hidden". Do place it back.

functionhomeSelected(){
const home = document.getElementById("homeSelector").value;

if(home == 5){
document.getElementById("amountNeeded").value = 300;
}else{
document.getElementById("amountNeeded").value = 100;
}
}
<selectid="homeSelector"name="HomeState"onchange="homeSelected()"required><optionvalue="1">Alabama</option><optionvalue="1">Alaska</option><optionvalue="1">Arizona</option><optionvalue="1">Arkansas</option><optionvalue="5">California</option><optionvalue="1">Colorado</option><optionvalue="1">Connecticut</option><optionvalue="1">Delaware</option></select><inputid="amountNeeded"name="AmountNeeded"value="100" />

Solution 2:

You can do this as follows:

<selectname="HomeState"requiredonChange=myFunction(this)><optionvalue="1">Alabama</option><optionvalue="1">Alaska</option><optionvalue="1">Arizona</option><optionvalue="1">Arkansas</option><optionvalue="5">California</option><optionvalue="1">Colorado</option><optionvalue="1">Connecticut</option><optionvalue="1">Delaware</option></select>

Javascript code is:

<script>functionmyFunction(x) {

  val =  x.options[x.selectedIndex].text;

  if(val == 'California')
    document.getElementsByName("AmountNeeded")[0].value = 300elsedocument.getElementsByName("AmountNeeded")[0].value = 100
}
</script>

If else statement is good for you if you are sure that All other states have value 1 except California. If all states may have different values like some states may have 1 or some may have 2 or some may have 3, then there may be other alternatives to solve this like you can pass give one more attribute data-src-amount to options and give amount to data-src-amount. You can create options like <option value="1" data-src-amount="100">Alabama</option> and in script, you can fetch data-src-amount on select change event instead of if-else statement.

Post a Comment for "How Do You Pass A Value To A Hidden Form Field When A Certain Option Is Selected?"