I am attempting to change the value of a text input based on the user selecting a value from a pulldown. I have got it working using the following,
<script type="text/javascript">
$(document).ready(function() {
$("#name").live("change", function() {
$("#firstname").val($(this).find("option:selected").attr("value"));
})
});
</script>
<select id="name" name="name">
<option value="">Please select...</option>
<option value="Elvis">Elvis</option>
<option value="Frank">Frank</option>
<option value="Jim">Jim</option>
</select>
<input type="text" id="firstname" name="firstname" value="" readonly="readonly">
This all work fine. What I am trying to achieve now is for the pre-selected item to show by default when the user re-visits the form if they wish to edit their choice. At the moment the select just defaults to 'Please Select...'. Is their anyway to force the select to show the value from the text input when the page loads?
Thanks
Chris
$(document).ready(function() {
$(document).on("change", "#name", function() {
$("#firstname").val( this.value ); // this.value is enough for you
}).val( $('#firstname').val() ).change(); // for pre-selection trigger
});
Instead of .live()
use .on()
with jQuery 1.7+, because live()
is deprecated.
Syntax of .on()
for delegate event handling is:
$(StaticParent).on( eventName, target, handlerFunction );
Where, StaticParent
means the non-dynamic parent container of target
element on which you want to bind event.
So, for above case it would be better to use any static parent of #name
instead of document
.
Try this,
$(document).ready(function() {
$("#name option").filter(function() {
return $(this).val() == $("#firstname").val();
}).attr('selected', true);
$("#name").live("change", function() {
$("#firstname").val($(this).find("option:selected").attr("value"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<select id="name" name="name">
<option value="">Please select...</option>
<option value="Elvis">Elvis</option>
<option value="Frank">Frank</option>
<option value="Jim">Jim</option>
</select>
<input type="text" id="firstname" name="firstname" value="Elvis" readonly="readonly">
$(document).ready(function() {
$("#name").live("change", function() {
$("#firstname").val($(this).val());
})
});
Give this one a try: http://jsfiddle.net/ufomammut66/mw4dY/
Basically onload I'm just selecting an option by the value, setting it to selected and then calling the change event. Your change event takes care of the rest.
$(document).ready(function() {
$("#name").live("change", function() {
$("#firstname").val($(this).find("option:selected").attr("value"));
});
$('#name option[value=Frank]').attr('selected','selected').change();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With