基于选择属性的选择输入更改文本框值

我试图根据用户从下拉菜单中选择一个值来更改文本输入的值。 我使用以下工具,

 $(document).ready(function() { $("#name").live("change", function() { $("#firstname").val($(this).find("option:selected").attr("value")); }) });   Please select... Elvis Frank Jim   

这一切都很好。 我现在想要实现的是,如果用户希望编辑他们的选择,则在用户重新访问表单时默认显示预选项目。 目前,select只是默认为’Please Select …’。 无论如何,他们强制select在页面加载时显示文本输入的值?

谢谢

克里斯

试试这个,

 $(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")); }); }); 
    
 $(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 }); 

注意

而不是.live()使用.on()和jQuery 1.7+,因为不推荐使用live()

委托事件处理的.on()语法是:

 $(StaticParent).on( eventName, target, handlerFunction ); 

其中, StaticParent表示要绑定事件的target元素的非动态父容器。

因此,对于上述情况,最好使用#name任何静态父代替document

 $(document).ready(function() { $("#name").live("change", function() { $("#firstname").val($(this).val()); }) }); ​ 

尝试一下这个: http : //jsfiddle.net/ufomammut66/mw4dY/

基本上onload我只是按值选择一个选项,将其设置为选中,然后调用change事件。 您的更改活动负责其余部分。

 $(document).ready(function() { $("#name").live("change", function() { $("#firstname").val($(this).find("option:selected").attr("value")); }); $('#name option[value=Frank]').attr('selected','selected').change(); }); 

将此代码粘贴到$(document).ready

 $("#name").val($("#firstname").val()); 
 $('#name').val($('#firstname').val()); 

要记住表单值,您可以使用cookie函数 :

 $(document).ready(function() { var value = readCookie('fname'); if (value) { $("#firstname").val(value); $('#name option[value="'+value+'"]').prop('selected', true); } $("#name").on("change", function() { var value = $(this).find("option:selected").attr("value"); $("#firstname").val(value); createCookie('fname',value,31); }); }); function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } 

jsfiddle - 如果您再次访问此页面,该名称将在页面离开时返回。