I have the following jQuery code which has a link and a checkbox.
When the edit link is clicked it gets the data attribute on the link and checks the checkbox accordingly.
I also need the functionality to change the value of the checkbox if it is checked or unchecked by the user. So on change it's value gets amended to 1 or 0.
Issue
if I uncheck the box, the value becomes 0 as expected but then if I click the link again the checkbox doesn't become unchecked.
How To Replicate
See the jsFiddle
- Click the link
- Uncheck the checkbox
- Click the link again
I am expecting the checkbox to be checked as per the if( changecheckboxvalto == 1 )
condition.
Code
$('body').on('click', '#edit', function() {
// Get the change checkbox val
changecheckboxvalto = $(this).attr('data-changecheckboxvalto');
console.log('changecheckboxvalto = ' + changecheckboxvalto);
if( changecheckboxvalto == 1 ) {
$('#myinput').val(1).attr('checked', true);
} else {
$('#myinput').val(0).attr('checked', false);
}
// click checkbox makes chekbox value change to 1 or 0
$('#myinput').change(function() {
console.log('change happened');
if( $(this).val() == 0 ) {
$(this).val(1).attr('checked', true);
console.log('change condition 1');
} else {
$(this).val(0).attr('checked', false);
console.log('change condition 2');
}
});
});
Aucun commentaire:
Enregistrer un commentaire