Ra *_*Tre 9 javascript checkbox jquery onclick
我有一个表单,我想通过选中一个复选框来禁用或隐藏两个输入字段.我可以在document.ready上轻松完成,但由于我追加这些字段,该功能不会生效.如何使用onClick调用该函数?
这是我的工作代码
$(function() {
$(checkbox).click(function() {
if ($('#checkbox').is(':checked')) {
$('#appTimes').find('input').attr('disabled', true);
} else {
$('#appTimes').find('input').removeAttr('disabled');
}
});
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="appTimes" id="appTimes">
<input name="stopTime1" type="text" id="stopTime1" />
<input name="stopTime12" type="text" id="stopTime12" />
</div>
<input name="checkbox" type="checkbox" id="checkbox" />
Run Code Online (Sandbox Code Playgroud)
这就是我想要做的事情:
function boxDisable(e) {
$(this).click(function() {
if ($(this).is(':checked')) {
$(e).find('input').attr('disabled', true);
} else {
$(e).find('input').removeAttr('disabled');
}
});
}
Run Code Online (Sandbox Code Playgroud)
<div class="appTimes" id="appTimes">
<input name="stopTime1" type="text" id="stopTime1" />
<input name="stopTime12" type="text" id="stopTime12" />
</div>
<input name="checkbox" onclick="boxdisable(appTimes);" type="checkbox" id="checkbox" />
Run Code Online (Sandbox Code Playgroud)
---编辑---------------
让我重新定义:我的代码正在使用.追加以创建上述代码的多个实例.由于追加量是无限的,我无法定义复选框$('#id')
,因为可能有数百个喜欢$('#id1')
,$('#id2')
等等.我需要一个避免提及确切元素id的函数,被复选框调用onClick并影响前额div,也是附加的.
Max*_*rok 10
有用 :)
function boxDisable(e, t) {
if (t.is(':checked')) {
$(e).find('input').attr('disabled', true);
} else {
$(e).find('input').removeAttr('disabled');
}
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="appTimes" id="appTimes">
<input name="stopTime1" type="text" id="stopTime1" />
<input name="stopTime12" type="text" id="stopTime12" />
</div>
<input name="checkbox" onclick="boxDisable(appTimes, $(this));" type="checkbox" id="checkbox" />
Run Code Online (Sandbox Code Playgroud)
如果在文档准备好时元素不存在,请使用.on
,如下所示:
$(document).ready(function(){
$(document).on('change', 'input[type="checkbox"]', function(e){
//do your stuff here
});
});
Run Code Online (Sandbox Code Playgroud)