We're having an issue trying to chain selectors together. We are trying to get all checkboxes that are checked and have the data-action attribute with hideplan as the value. I've got a page that has two checkboxes, one button and this javas开发者_JAVA技巧cript on it:
<script type="text/javascript">
var hiddenplans = $('input:checkbox[data-action="hideplan":checked');
$("#hide_btn").click(function() {
hiddenplans.each(
function(index) {
alert('checked' + index);
});
});
</script>
This doesn't display any alerts when one or more checkboxes are selected - hiddenplans is empty. However, if we copy $('input:checkbox[data-action="hideplan":checked');
and put it into the firebug console and run it we will get results if one or more checkboxes are selected. If I remove :checked it will alert for checkboxes with data-action=hideplan.
We've tried several different ways of writing the selector (i.e. $("input[type=checkbox][data-action=hideplan]:checked")
and $("input[type=checkbox][data-action=hideplan]").filter(":checked");
and more) and they work in the console but will not return alerts.
I've created a Fiddle with the full code in case we missed something obvious http://jsfiddle.net/xCnSs/5/
Try this...
$('input:checkbox[data-action="hideplan"]:checked')
jsFiddle.
You're caching the selected set in a variable so it will only return which items are checked on page load. Move this selector into your click function and it will work:
$("#hide_btn").click(function () {
var hiddenplans = $("input[type=checkbox][data-action=hideplan]:checked");
hiddenplans.each(function (index) {
alert('checked' + index);
});
});
http://jsfiddle.net/xCnSs/6/
You forgot the closing bracket:
$('input:checkbox[data-action="hideplan"]:checked');
But remember you can also filter results:
$('input:checkbox[data-action="hideplan"]').filter(':checked');
精彩评论