Javascript function to uncheck/clear all checkboxes selected from a button

Asked

Viewed 6,659 times

0

I have several checkboxes in a form, which will be marked by the user. If you want, you can clear them all by clicking on a button, as shown below: checkboxes

tried using this function in javascript:

function myFunctionClear() {
  for (i = 0; i < document.selecao.elements.length; i++)
    if (document.selecao.elements[i].type == "checkbox")
      document.selecao.elements[i].checked = 0
}

on my button

<button class='btn  custom' onclick="myFunctionClear()">Limpar Seleção</button>

but for some reason it’s not working. Stackoverflow’s other answer I found (Check/Deselect Checkbox from a button) shows a button that marks and marks all checkboxes, but I only want the option to uncheck. link to the jsfidlle: https://jsfiddle.net/elenderg/tdvqp4xL/

2 answers

2


You must remove the attribute checked

function myFunctionClear() {
  for (i = 0; i < document.selecao.elements.length; i++)
    if (document.f1.elements[i].type == "checkbox")
      document.f1.elements[i].removeAttribute("checked");
}

Or mark it as false

function myFunctionClear() {
  for (i = 0; i < document.selecao.elements.length; i++)
    if (document.f1.elements[i].type == "checkbox")
      document.f1.elements[i].checked = false;
}

UPDATE

I assumed that document.f1 represented the tag <form> that has checkboxes to be unchecked. The code below is based on the example https://jsfiddle.net/elenderg/tdvqp4xL/

First: Replace the form you entered within another form

    <form action="form_action.asp">
      <form name="selecao">

for:

    <form action="form_action.asp" name="selecao">

Second: Rewrite the function myFunctionClear

function myFunctionClear() {
  for (i = 0; i < document.forms.selecao.elements.length; i++)
    if (document.forms.selecao.elements[i].type == "checkbox")
      document.forms.selecao.elements[i].checked = false;
}

1

There is a simpler, more performative way to do this without using a for to deselect these selected fields. Take a look:

function myFunctionClear() {
  var inputs = $('input[type=checkbox]');

  inputs.attr('checked', false);
  inputs.prop('checked', false);
}
  • This solution works but I think it is too expansive once it captures all the checkboxes on the page. The line inputs.prop('checked', false); has no effect in that context and could be removed.

  • I understand your point, and you are really right. But I have already used this solution in an application that perfectly met the requirement... Then I guess it’s more of a necessity anyway. The line inputs.prop('checked', false); I added only as a guarantee, I believe that if the function is called twice, the second would not behave as expected without that line, but it is worth the test :)

Browser other questions tagged

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