Checkbox filled

Asked

Viewed 74 times

0

I have a script that the user inform the ID fields are completed: name and inactive, if the user has marked the inactive checkbox when registering return the checkbox filled and if you have not checked the checkbox returnit without checking, however my function always returns the checkbox filled

<script type='text/javascript'>
    $(document).ready(function(){
            $("input[name='id']").blur(function(){
                    var $nome = $("input[name='nome']");
                    var $inativo = $("input[name='inativo']");

                    $.getJSON('function_pes.php',{ 
                            id: $( this ).val() 
                    },function( json ){
                            $nome.val( json.nome );
                            $inativo.prop('checked', json.inativo );

                    });
            });
    });

  • See if the "inactive" JSON field is coming in quotes, e.g. "true" or "false". prop("checked", json.inactive), it is only checking whether the "inactive" JSON field exists, which is always true, then the check is marked.

  • I checked in Inspect > Network and my return was this > {"name":"THIAGO SILVA","inactive":"0"} but I have the checkbox return marked, it is really what is happening, could tell me what to do

1 answer

1


The problem is that the "inactive" JSON field is coming like this: "inativo":"0". The . prop("checked", ...) method gets a Boolean, so we have to convert this "0" to Boolean first, using double negative, as follows:

!!1 = true; // negativa dupla em 1 vira verdadeiro
!!0 = false; // negativa dupla em 0 vira falso

But only that is not enough, because the value is as string, so before we convert to int by putting a "+" in front, then the end result is like this:

$inativo.prop('checked', !!+json.inativo );
  • thank you, besides healing the doubt still taught me and pointed out the error, too grateful for the help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.