New to javascript, but I'm sure this is easy. Unfortunately, most of the google results haven't been helpful.
Anyway, I want to set the value of a hidden form element through javascript when a drop down selection changes.
I can use jQuery, if it makes it simpler to get or set the values.
The <input type="hidden"> defines a hidden input field. A hidden field lets web developers include data that cannot be seen or modified by users when a form is submitted. A hidden field often stores what database record that needs to be updated when the form is submitted.
The <input> element's value attribute holds a string that contains the hidden data you want to include when the form is submitted to the server. This specifically can't be edited or seen by the user via the user interface, although you could edit the value via browser developer tools.
If you have HTML like this, for example:
<select id='myselect'> <option value='1'>A</option> <option value='2'>B</option> <option value='3'>C</option> <option value='4'>D</option> </select> <input type='hidden' id='myhidden' value=''>
All you have to do is bind a function to the change
event of the select, and do what you need there:
<script type='text/javascript'> $(function() { $('#myselect').change(function() { // if changed to, for example, the last option, then // $(this).find('option:selected').text() == D // $(this).val() == 4 // get whatever value you want into a variable var x = $(this).val(); // and update the hidden input's value $('#myhidden').val(x); }); }); </script>
All things considered, if you're going to be doing a lot of jQuery programming, always have the documentation open. It is very easy to find what you need there if you give it a chance.
Plain old Javascript:
<script type="text/javascript"> function changeHiddenInput (objDropDown) { var objHidden = document.getElementById("hiddenInput"); objHidden.value = objDropDown.value; } </script> <form> <select id="dropdown" name="dropdown" onchange="changeHiddenInput(this)"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> <input type="hidden" name="hiddenInput" id="hiddenInput" value="" /> </form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With