jQuery根据页面加载时选择的选项设置输入值属性

时间:2013-04-04 09:15:46

标签: jquery

我需要将输入值属性设置为在选择菜单中选择的选项

<select id="choice">
    <option value="10">10</option>
    <option value="20">20</option>
    <option value="50">50</option>
</select>
<input type='text' id="other" class="test" value=""/>

我正在使用的jQuery是

var option = $('#choice').find(":selected").text();
$('#other').val(option);

$('#choice').change(function () {
    var selected_item = $(this).val()
    $('#other').val(selected_item);
    $('#other').attr('value', $('#choice').val())
});

这会在页面加载时设置输入值。但value属性仅在.change事件上设置。当页面加载到当前选择选项时,我还需要设置输入的value属性。

http://jsfiddle.net/peter/LaTXG/2/

由于

2 个答案:

答案 0 :(得分:1)

$('#choice').on('change', function () {
    $('#other').val(this.value);
}).trigger('change');

FIDDLE

将文本输入值设置为选择值,包括页面加载和更改。

答案 1 :(得分:-1)

使用setTimeout

setTimeout(function(){
var option = $('#choice').find(":selected").val();
$('#other').val(option);
},500);
相关问题