user3023588 user3023588 - 7 months ago 14
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:

HTML:

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


JQuery:

$( 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

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

Documentation here: https://api.jquery.com/change/

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