How to set the change state of a checkbox switchery using Javascript and Asp.Net Core MVC

Asked

Viewed 101 times

0

I have several checkbox switchery components that are automatically created in which I control the ID manually, in theory, a list of elements. I need to do the following: When unchecking one of the checkboxes of a Row, the change event will be triggered and a loop will loop through all other checkboxes and must "deselect" the other checkboxes.

inserir a descrição da imagem aqui

I have tried to remove checked as below, but it did not work. I don’t know if it’s a switchery component thing, but removing or not the checked tag doesn’t seem to change the state of the component.

$('#PessoaViewModel_PessoasEnderecosViewModel_" + indice + "__EnderecoPrincipal').attr('checked','');

On Asp.net, I’m doing it this way with Razor:

<div class="col-md-2">
    <input type="checkbox" class="ckb-endereco-principal" name="PessoaViewModel.PessoasEnderecosViewModel[@(i)].EnderecoPrincipal" id="PessoaViewModel_PessoasEnderecosViewModel_@(i)__EnderecoPrincipal" data-plugin="switchery" data-size="small" @(Model[i].EnderecoPrincipal ? "checked=\"checked\"" : "")/>
    <label asp-for="@Model[i].EnderecoPrincipal" class="control-label lb-endereco-principal">Principal</label>
</div>

And below, follow the JS script:

$("#div-enderecos").on("change", ".ckb-endereco-principal", function () {
    var enderecoTipo = $(this).closest('.row').find('.sel-endereco-tipo').val();      

    $("#div-enderecos .row").each(function (indice, elemento) {

        if ($(this).closest('.row').find('.sel-endereco-tipo').val() === enderecoTipo) {
            $("#PessoaViewModel_PessoasEnderecosViewModel_" + indice + "__EnderecoPrincipal").attr('checked', '');
        }            
    });
});

Someone knows how to help me?

A hug to all :)

1 answer

0

The problem is when assigning the value in checkbox switchery. The correct would be to inform a boolean, and not a string. The correct then would be:

$("#PessoaViewModel_PessoasEnderecosViewModel_" + indice + "__EnderecoPrincipal").attr('checked', false);

Display a Alert with the value of checked, you will see that he will return one bool.

alert($("#PessoaViewModel_PessoasEnderecosViewModel_" + indice + "__EnderecoPrincipal").checked);

This will return a Alert with true or false.

  • Reference 1: http://abpetkov.github.io/switchery/ Reference 2: https://stackoverflow.com/questions/5270689/attrchecked-checked-does-not-work

  • Thanks for the @Jonathan feedback from Toni, but unfortunately it didn’t work... According to your suggestion and the way I was doing, the script removes only the 'checked' tag, but the checkbox does not update and remains flagged as if it were active.. You gotta do something that shoots some kind of refresh... I don’t know.

Browser other questions tagged

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