jeudi 17 mars 2016

Setting checkbox state based on values from ajax response

I am getting values (1 or 0) from my database via ajax/jquery and I want to set a bunch of checkbox checked states depending on the values returned for each.

So firstly, I am setting the values for all checkboxes. Then I run a function to set the checkbox checked state based on the values. When I try this, all checkboxes are checked regardless of value:

Snippet of my Ajax response (jQuery)

    .success(function(response) {
        $('input').removeClass('error').next('.errormessage').html('');
        if(!response.errors && response.result) {
            $.each(response.result, function( index, value) {

                $("#checkbox1").prop('value',value[2]);
                $("#checkbox2").prop('value',value[3]);
                $("#checkbox3").prop('value',value[4]);
                $("#checkbox4").prop('value',value[5]);

           });
            $("#div :checkbox").each(function () {
                 if ($(this).attr('value', '1')){
                     $(this).attr('checked', true);
                 }
                 else
                  if ($(this).attr('value', '0')){
                     $(this).attr('checked', false);
                 }
                }); 
        } else {
            $.each(response.errors, function( index, value) {
                $('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
            });

        }
    });




Aucun commentaire:

Enregistrer un commentaire