Checkbox completed

0

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

<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 );

                    });
            });
    });

    
asked by anonymous 11.10.2017 / 16:27

1 answer

1

The problem is that the "inactive" JSON field is coming like this: "inativo":"0" . The .prop ("checked", ...) method receives 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 this is not enough, because the value is a string, so before converting to int by putting a "+" in front, then the end result looks like this:

$inativo.prop('checked', !!+json.inativo );
    
11.10.2017 / 18:37