0

Unfortunately i'm not too familiar with javascript/jQuery. I have a form with a dropdown. What i need to do is to populate a text field depending on the selection of the dropdown. First voice of the dropdown is "other" so the text field must be writable, then from the second i want to assign a value automatically and disable the text field.

The value of the dropdown will be saved in the db so it must remains the name of the option.

I found several solutions with google but none of them fits my needs...hope someone could help me.

4

2 回答 2

2

要创建您正在寻找的功能,您需要学习一些基本知识。

jQuery 选择器

首先,如果您还不熟悉 jQuery 的选择器语法,请在此处了解它

.change() 事件

接下来,您需要知道如何绑定到下拉菜单的.change事件。一种方法是$('#dropdownId').change(function() { ... });,这只是$('#dropdownId').on('change', function() { ... });. 在回调函数中,您可以this使用$(this).

然后,我们可以使用 $(this).val() 获取下拉列表的值,并使用一些基本逻辑来启用/禁用文本框并设置其值。

启用/禁用文本框

为了启用/禁用文本框,您可以使用: $('#txt').removeAttr('disabled'); and$('#txt').attr('disabled', 'true');` 分别。

示例
我在一个示例小提琴中为您组合了所有这些,以向您展示如何将它们放在这个jsFiddle中。如果您对它的工作原理有任何疑问,请告诉我:)

于 2013-07-31T10:56:01.923 回答
1

这是给你的小提琴......

http://jsfiddle.net/G3V3v

HTML

<select id="ddl">
    <option value="0">[ Other ]</option>
    <option value="1">First</option>
    <option value="2">Second</option>
</select>
<input id="txt" />

jQuery :

$('#ddl').change(function() {
    if ($(this).val() == 0) {
        $('#txt').val('').removeAttr("disabled").focus();
    } else {
        $('#txt').val($(this).children('option:selected').text());
        $('#txt').attr("disabled", "disabled");
    }
});
于 2013-07-31T10:49:34.597 回答