How to simulate onclick checkbox

Asked

Viewed 761 times

1

Good morning People, I have a form that is a datatable, and I have a button that marks or unchecks, all checkboxes of this datatable, by default these checkboxes are marked, i need that when reading the page or clicking on the button mark all the checkbox change its property by simulating a click on each checkbox. follows below my button. It has as?

Function marcardesmarcar() {

$('.marcar').each(function () {
    if (this.checked) 
       $(this).attr("checked", false);
    else 
       $(this).prop("checked", true);
});

}

4 answers

1

    $(document).ready(function() {
      toggleCheckBoxs(); // inicia alternando os checks boxs
    });


    function toggleCheckBoxs(){
      var checks = $('input');
      // checks.map((i,x) => x.checked = !x.checked );
      checks.map((i,x) => $(x).click() ); // aqui dispara o evento de click
    }

Check here: test

  • this function that I use already does the same as yours, my doubt is if your answer will simulate the event click, in checksboxs

  • um, got it, updated the response.

0


Good people after much studying, I managed to solve using the function below.

Function marcardesmarcar() {

$('.marcar').on('click', function () {
    if (this.checked) 
       $(this).attr("checked", false);
    else 
       $(this).prop("checked", true);
});
// Chama a função de clique através do trigger
$('.marcar').trigger('click');

}

0

You can use this way, automatically when marking your CheckBox, he seeks all others and marks the same value of his checkbox clicked:

$("#marcar").click(function(){
    $('input:checkbox').not(this).prop('checked', this.checked);
});

  • not so, because I need to go through the datatable, $('. mark'). each(Function(), . mark I use the class

  • And why do you wear .prop() in an if and in Else you use the .attr()?

  • sorry I was testing and forgot to reverse,

0

I can help you by showing you how you can do it with JS Vanilla:

// Pega todos os elementos com a class .marcar
const marcar = document.querySelectorAll('.marcar')

//Transforma a HTMLCollection em array e intera cada item
Array.from(marcar).forEach(el => {
  // Checa o valor de cada elemento
  let isChecked = el.checked
  return el.checked = !isChecked // Seta o atributo inverso do que está atual
})
  • I’ll do a search on JS Vanilla...

  • But that solves your problem?

Browser other questions tagged

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