2012-07-16 67 views
0

我有一个jsp页面。 我有一个数字选择列表。谁有一些默认值,但是是动态生成的。 我也有一个文本字段。 我希望文本字段应该完全按照选择列表中选定的选项自动填充。我正在使用jQuery来做到这一点。如何正确填写选择列表中选定的选项..?

但我看到,当jsp页面加载时,选择列表有其默认值,但文本字段为空。只有当我更改选项时,文本字段才会填充选定的选项。我希望当页面加载文本字段时,也可以像选择列表一样填充动态生成的选项。

我的脚本标签中的jQuery代码:

$(document).ready(function(){ 
       $("#select_id").change(function() { 
        $("#textfield_id").val($("#select_id option:selected").text()); 
       });}); 

任何一个可以建议我应该怎么办?简单地初始化文本字段无论下拉列表中的值在DOM准备绑定到前 -

+0

一些人能解决这个问题以及..感谢.. http://stackoverflow.com/questions/11641662/doccookie-is-not-getting-saved-instantly – codeofnode 2012-07-25 12:04:07

回答

1
$(document).ready(function() { 
    $("#select_id").change(function() { 

     // this -> refers to the select field 

     $("#textfield_id").val(this.value); 
     // or 
     $("#textfield_id").val($('option:selected', this).text()); 
    }).change(); // .change() is for trigger an initial change event after page load 
       // to update the textfield value 
}); 
0

喜欢这个名字所暗示的,.change()当元素的值更改只会被解雇变化事件。另外,请考虑使用jQuery .val()方法获取/设置表单元素的值。

$(document).ready(function(){ 

    $("#textfield_id").val($("#select_id").val()); 

    $("#select_id").change(function() { 
     $("#textfield_id").val($(this).val()); 
    }); 
}); 
相关问题