Javascript jQuery复选框选中状态改变事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8423217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery checkbox checked state changed event
提问by AnonyMouse
I want an event to fire client side when a checkbox is checked / unchecked:
我想要一个事件在选中/取消选中复选框时触发客户端:
$('.checkbox').click(function() {
if ($(this).is(':checked')) {
// Do stuff
}
});
Basically I want it to happen for every checkbox on the page. Is this method of firing on the click and checking the state ok?
基本上我希望它发生在页面上的每个复选框中。这种点击触发并检查状态的方法好吗?
I'm thinking there must be a cleaner jQuery way. Anyone know a solution?
我认为必须有一种更清洁的 jQuery 方式。有人知道解决方案吗?
回答by James Allardice
Bind to the change
event instead of click
. However, you will probably still need to check whether or not the checkbox is checked:
绑定到change
事件而不是click
. 但是,您可能仍需要检查是否选中了复选框:
$(".checkbox").change(function() {
if(this.checked) {
//Do stuff
}
});
The main benefit of binding to the Redacted in commentschange
event over the click
event is that not all clicks on a checkbox will cause it to change state. If you only want to capture events that cause the checkbox to change state, you want the aptly-named change
event.
绑定到在评论中编辑change
事件click
而不是事件的主要好处是并非所有单击复选框都会导致其更改状态。如果您只想捕获导致复选框更改状态的事件,则需要恰当命名的change
事件。
Also note that I've used this.checked
instead of wrapping the element in a jQuery object and using jQuery methods, simply because it's shorter and faster to access the property of the DOM element directly.
另请注意,我使用this.checked
而不是将元素包装在 jQuery 对象中并使用 jQuery 方法,仅仅是因为直接访问 DOM 元素的属性更短、更快。
Edit(see comments)
编辑(见评论)
To get all checkboxes you have a couple of options. You can use the :checkbox
pseudo-selector:
要获取所有复选框,您有几个选项。您可以使用:checkbox
伪选择器:
$(":checkbox")
Or you could use an attribute equalsselector:
或者您可以使用属性等于选择器:
$("input[type='checkbox']")
回答by applecrusher
For future reference to anyone here having difficulty, if you are adding the checkboxes dynamically, the correct accepted answerabove will not work. You'll need to leverage event delegationwhich allows a parent node to capture bubbled events from a specific descendant and issue a callback.
为了将来参考这里有困难的任何人,如果您动态添加复选框,则上面的正确接受答案将不起作用。您需要利用允许父节点从特定后代捕获冒泡事件并发出回调的事件委托。
// $(<parent>).on('<event>', '<child>', callback);
$(document).on('change', '.checkbox', function() {
if(this.checked) {
// checkbox is checked
}
});
Note that it's almost always unnecessary to use document
for the parent selector. Instead choose a more specific parent node to prevent propagating the event up too many levels.
请注意,它几乎总是没有必要document
用于父选择器。而是选择一个更具体的父节点,以防止将事件传播到太多级别。
The example below displays how the events of dynamically added dom nodes do not trigger previously defined listeners.
下面的示例显示了动态添加的 dom 节点的事件如何不触发先前定义的侦听器。
$postList = $('#post-list');
$postList.find('h1').on('click', onH1Clicked);
function onH1Clicked() {
alert($(this).text());
}
// simulate added content
var title = 2;
function generateRandomArticle(title) {
$postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');
}
setTimeout(generateRandomArticle.bind(null, ++title), 1000);
setTimeout(generateRandomArticle.bind(null, ++title), 5000);
setTimeout(generateRandomArticle.bind(null, ++title), 10000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="post-list" class="list post-list">
<article class="post">
<h1>Title 1</h1>
</article>
<article class="post">
<h1>Title 2</h1>
</article>
</section>
While this example displays the usage of event delegation to capture events for a specific node (h1
in this case), and issue a callback for such events.
虽然此示例显示了使用事件委托来捕获特定节点(h1
在本例中)的事件,并为此类事件发出回调。
$postList = $('#post-list');
$postList.on('click', 'h1', onH1Clicked);
function onH1Clicked() {
alert($(this).text());
}
// simulate added content
var title = 2;
function generateRandomArticle(title) {
$postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');
}
setTimeout(generateRandomArticle.bind(null, ++title), 1000); setTimeout(generateRandomArticle.bind(null, ++title), 5000); setTimeout(generateRandomArticle.bind(null, ++title), 10000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="post-list" class="list post-list">
<article class="post">
<h1>Title 1</h1>
</article>
<article class="post">
<h1>Title 2</h1>
</article>
</section>
回答by Siddhartha Chowdhury
Just another solution
只是另一种解决方案
$('.checkbox_class').on('change', function(){ // on change of state
if(this.checked) // if changed state is "CHECKED"
{
// do the magic here
}
})
回答by Matas Vaitkevicius
If your intention is to attach event only on checked checkboxes (so it would fire when they are unchecked and checked later again) then this is what you want.
如果您的意图是仅在选中的复选框上附加事件(因此它会在取消选中并稍后再次选中时触发),那么这就是您想要的。
$(function() {
$("input[type='checkbox']:checked").change(function() {
})
})
if your intention is to attach event to all checkboxes (checked and unchecked)
如果您打算将事件附加到所有复选框(选中和未选中)
$(function() {
$("input[type='checkbox']").change(function() {
})
})
if you want it to fire only when they are being checked (from unchecked) then @James Allardice answer above.
如果您希望它仅在它们被检查(从未检查)时触发,那么@James Allardice 在上面回答。
BTW input[type='checkbox']:checked
is CSS selector.
BTWinput[type='checkbox']:checked
是 CSS 选择器。
回答by Burhan Kaya
$(document).ready(function () {
$(document).on('change', 'input[Id="chkproperty"]', function (e) {
alert($(this).val());
});
});
回答by Hasib Kamal
Action taking based on an event (on click event).
基于事件(点击事件)采取的行动。
$('#my_checkbox').on('click',function(){
$('#my_div').hide();
if(this.checked){
$('#my_div').show();
}
});
Without event taking action based on current state.
没有事件根据当前状态采取行动。
$('#my_div').hide();
if($('#my_checkbox').is(':checked')){
$('#my_div').show();
}
回答by caras
perhaps this may be an alternative for you.
也许这可能是您的替代方案。
<input name="chkproperty" onchange="($(this).prop('checked') ? $(this).val(true) : $(this).val(false))" type="checkbox" value="true" />`
回答by Shan
This is the solution to find is the checkbox is checked or not. Use the #prop() function//
这是要查找是否选中复选框的解决方案。使用#prop() 函数//
$("#c_checkbox").on('change', function () {
if ($(this).prop('checked')) {
// do stuff//
}
});
回答by Radames E. Hernandez
Is very simple, this is the way I use:
很简单,我是这样使用的:
JQuery:
查询:
$(document).on('change', '[name="nameOfCheckboxes[]"]', function() {
var checkbox = $(this), // Selected or current checkbox
value = checkbox.val(); // Value of checkbox
if (checkbox.is(':checked'))
{
console.log('checked');
}else
{
console.log('not checked');
}
});
Regards!
问候!
回答by N?s????? ?
Try this jQuery validation
试试这个 jQuery 验证
$(document).ready(function() {
$('#myform').validate({ // initialize the plugin
rules: {
agree: {
required: true
}
},
submitHandler: function(form) {
alert('valid form submitted');
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<form id="myform" action="" method="post">
<div class="buttons">
<div class="pull-right">
<input type="checkbox" name="agree" /><br/>
<label>I have read and agree to the <a href="https://stackexchange.com/legal/terms-of-service">Terms of services</a> </label>
</div>
</div>
<button type="submit">Agree</button>
</form>