基于具有选定属性的选择输入来更改文本框值 [英] Change Text Box Value Based on Select Input with Selected Attribute

查看:55
本文介绍了基于具有选定属性的选择输入来更改文本框值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据用户从下拉菜单中选择一个值来更改文本输入的值.我已经使用以下方法使其工作了,

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?

谢谢

克里斯

推荐答案

尝试一下,

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

这篇关于基于具有选定属性的选择输入来更改文本框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆