updating a input field based on selectlist option
I have the following HTML
<select name="title" id="title">
<option value="Mrs" >Mrs</option>
<option value="Mr" >Mr</option>
<option value="Miss" >Miss</option>
<option value="Dr" >Dr</option>
</select>
<input type="text" name="gtitle" id="gift_title" value="" />
Now by default Mrs
is shown as the first option of the select list. What I need开发者_如何学Go to do then, is to get this value and display it in the input
field. Subsequent selections by the user, i.e he/she choses Mr
, must also update this input field as well.
I was hoping I could this in jQuery, but I wasn't sure how to get these values.
Thanks
You could subscribe for the .change()
event of the dropdownlist and update the value of the input:
$(function() {
// initialize the value of the input field to the selected value
// of the dropdown list:
$('#gift_title').val($('#title').val());
$('#title').change(function() {
// when the value of the dropdown list changes
// update the input field
$('#gift_title').val($(this).val());
});
});
And here's a live demo.
In addition to the awnsers provided already, I suggest the following, to populate the input field with the default value of the checkbox at load. Insert something like this between line 4 and 5 of Darin's code:
$('#gift_title').val($('#title').val());
or consider making the change callback function explicit so it could be reused.
Hope this helps!
<select name="title" id="title">
<option value="Mrs" >Mrs</option>
<option value="Mr" >Mr</option>
<option value="Miss" >Miss</option>
<option value="Dr" >Dr</option>
</select>
<input type="text" name="gtitle" id="gift_title" value="Mrs" />
I added default value to html
$('#title').change(function(){
$('#gift_title').val(this.value);
});
working demo
but I fail to see any reason for this just use the select value when you submit there should be no need for input feild
精彩评论