user1098178 user1098178 - 4 months ago 31
jQuery Question

Change Text Box Value Based on Select Input with Selected Attribute

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

Answer

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">