user3023588 user3023588 - 1 year ago 69
Javascript Question

How to set value for hidden field based on selected option in drop down?

I have my drop down created in JQuery where I read values and names from array. That part works fine, now I would like to set value for hidden field that I placed above my select tag. So each time I change my option I have to set different value for that hidden field. Here is my code:


<input type="hidden" id="userID" name="user" value=""/>
<select id="selUser" name="selUser">
<option value="">--Select Student--</option>


$( document ).ready(function() {
var userValues = [];

userValues.push({'idOne':"31",'idTwo':"Tom, Poitras",'idThree':"88"});
userValues.push({'idOne':"16",'idTwo':"All, Dirks",'idThree':"89"});
userValues.push({'idOne':"15",'idTwo':"John, Reed",'idThree':"50"});

for(var i=0; i < studValues.length; i++){
$('#selUser').append('<option value='+userValues[i].idOne+'>'+userValues[i].idTwo+'</option>');

How I can set hidden value(idThree in my array) after I pick the student in my drop down? Should I have another function for that or there is some another approach for this problem? If anyone can help please let me know.

Answer Source

I'd suggest using jQuery's .change() event.

Documentation here:

Something like $('#selUser').change(function() { // what you want to do here }); inside your document.ready() function would attach an anonymous event to the dropdown.