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 to do then, is to get this value and display it in the input
field. Subsequent selections by the user, ie 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 .
<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);
});
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
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.