0

I am trying to check some checkboxes based on it value. In my code, I can update the database using this ckbxs, but when I try load the updated date, the status is showed as uncheck. So, I am trying to read the html, after create the form, to check the values and then check the ckbx. What can I do here to fix it? Thanks in advance

$(document).ready(function(){
    $('input[type=checkbox]').each(function () {
       if (this.value == 1) {
            (function(){this.attr('checked', true);})
        }
    } )
})
1
  • Not every version of jQuery supports the attribute selector correctly when the value of the attribute is unquoted. YMMV. Commented Oct 20, 2011 at 3:53

3 Answers 3

1

You need to enclose the thiss in a $( ) and change value to val().

$(document).ready(function(){
    $('input[type=checkbox]').each(function () {
       if ($(this).val() == 1) {
            $(this).attr('checked', true);
       }
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

You can add an onchange event to each checkbox and set the value based on whether it is checked or not
its work fine, but know i have a new problem. could you revise please ? Is not possible to set the value as 0. It is always returning 1. ` $(document).ready(function(){ $('input:checkbox').change(function() { $.post('update.php', { id: this.id, value: $(this).attr("checked")?1:0 }, function(data){ $('#display').html(data.returnValue) if(data.success) { } else { } }, 'json'); return false; }); $('input[type=checkbox]').each(function () { if ($(this).val() == 1) { $(this).attr('checked', true); } }); });`
Attributes are string values, so testing for a not-empty string will always return true whether the value is "true" or "false". Try changing $(this).attr("checked")?1:0 to $(this).attr("checked")=="true"?1:0
0
$(document).ready(function () {
    $('input[type="checkbox"][value="1"]').each(function () {
        $(this).attr('checked', true);
    });
});

Comments

0

Thanks Willian, now I am using a onChange and I got what I need...

function changerCB(idCheck){

$(document).ready(function() {
$.post('ajaxUpdate.php', {
    id: document.getElementById(idCheck).id,
    value: document.getElementById(idCheck).checked?1:0
    }, function(data){
        $('#display').html(data.returnValue)
        if(data.success) {              
    } else {
    }
}, 'json');
return false;  
}); 
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.