Reputation: 368
I have a few checkboxes (some already checked through html checked attribute) on a page and a submit button. I wanna use jquery to run a function using the $.each() loop such that it performs the function if the checkbox is checked, but only if it wasn't already checked. Also, I want to perform a function for each un checked check box, but only if it was already Checked.
Please help
Upvotes: 2
Views: 226
Reputation: 16561
One way of doing this is to use .data()
to store the original value of the checkbox.
$(document).ready(function(){
$("input[type='checkbox']").each(function(){
$(this).data("originalValue", $(this).is(":checked"));
})
});;
$("#ok").click(function(){
$("input[type='checkbox']").each(function(){
var edited = $(this).data("originalValue") !== $(this).is(":checked");
if (edited)
{
var checkboxLabel = $(this).next("label");
alert("edited: " + checkboxLabel.text());
}
});
});
http://jsfiddle.net/8g3uz/3/
Original solution that checks for user interaction rather than change: http://jsfiddle.net/8g3uz/1/
Upvotes: 5
Reputation: 253318
To react to only those checkboxes being checked that weren't originally checked, I'd suggest:
$('#check').click(
function(e){
e.preventDefault();
var checkboxes = $('input:checkbox:checked');
checkboxes.each(
function(i){
if (this.defaultChecked == false) {
// do something, it wasn't checked on page-load, eg:
alert("This is a checkbox that wasn't originally checked.");
}
});
});
To do something if the state has changed from the default, which seems to be the basis of your question:
$('#check').click(
function(e){
e.preventDefault();
var checkboxes = $('input:checkbox');
checkboxes.each(
function(){
if (this.defaultChecked !== this.checked) {
$(this).prev('label').addClass('changedFromDefault');
}
});
});
Using the following HTML:
<span>
<label for="one">one</label><input id="one" type="checkbox" checked />
</span>
<span>
<label for="two">two</label><input id="two" type="checkbox" />
</span>
<span>
<label for="three">three</label><input id="three" type="checkbox" />
</span>
<button id="check">Check</button>
This jQuery should show how to identify those elements that are changed, or unchanged, more easily:
$('#check').click(
function(e){
e.preventDefault();
var checkboxes = $('input:checkbox');
checkboxes.each(
function(){
if (this.defaultChecked !== this.checked) {
$(this)
.closest('span')
.removeClass('unchanged')
.addClass('changedFromDefault');
}
else {
$(this)
.closest('span')
.removeClass('changedFromDefault')
.addClass('unchanged');
}
});
});
References:
addClass()
.:checkbox
selector.:checked
selector.click()
.each()
.HTMLInputElement
(for the defaultChecked
property) at MDN.prev()
.Upvotes: 1
Reputation: 145398
Here is a selector for the first case:
$("input[type='checkbox']:not([checked]):checked");
Here is a selector for the second case:
$("input[type='checkbox'][checked]:not(:checked)");
DEMO: http://jsfiddle.net/fascw/
Upvotes: 0