Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to set hidden form value on drop down change

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.

like image 838
jerhinesmith Avatar asked May 02 '09 21:05

jerhinesmith


People also ask

How do you send a hidden value in a form?

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.

How we can pass hidden form field in the form data?

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.


2 Answers

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.

like image 156
Paolo Bergantino Avatar answered Oct 04 '22 07:10

Paolo Bergantino


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> 
like image 32
Jordan S. Jones Avatar answered Oct 04 '22 07:10

Jordan S. Jones