我有一个script,只要选择“是”单选按钮,它就会使文本区域变灰。我想修改jquery脚本,以便textarea可以位于不同的div中,并且仍然像以前一样被禁用。
通过查看jQuery文档,我可以使用.parent来执行此操作,但我无法使其正常工作。
<div class="group">
<input type="radio" name="choice2" value="yes" />Yes
<input type="radio" name="choice2" value="no" />No
</div>
<div class="group">
<textarea rows="4" cols="20"></textarea>
</div>
我怎样才能做到这一点?或者,还有更好的方法?
编辑:
$(function () {
var $choices = $(".group").find(":radio");
$choices.on("change", function () {
var $this = $(this);
var tarea = $this.closest(".group").next(".group").find("textarea");
if ($this.val() === "yes") {
tarea.val('');
tarea.prop('readonly', true);
tarea.css('background-color', '#EBEBE4');
} else {
tarea.prop('readonly', false);
tarea.css('background-color', '#FFFFFF');
}
});
});
最佳答案
为每个<textarea>
添加了属性“触发”。按名称确定其触发元素。例如,<textarea data-trigger="choice2">
表示<input name="choice2"/>
更改是凝视(灰色/否)。
这样,您可以在页面内的任何位置添加textarea元素,而无需担心。
这是一个示例:http://jsfiddle.net/r0gw8t1b/2/