JavaScript function to uncheck / clear all selected checkboxes from a [duplicate] button

0

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

Itriedtousethisfunctioninjavascript:

functionmyFunctionClear(){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 is not working. the other StackOverflow response I found ( Mark / Uncheck Checkbox from a button ) shows a button that marks and marks all checkboxes, but I only want the option to uncheck it. link to jsfidlle: link

    
asked by anonymous 22.02.2016 / 20:23

2 answers

2

You should remove the checked attribute

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 <form> tag that has the checkboxes to be deselected. The code below is based on the example link

First: Replace the form you entered inside another form

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

by:

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

Second: Rewrite 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;
}
    
22.02.2016 / 20:25
1

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

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

  inputs.attr('checked', false);
  inputs.prop('checked', false);
}
    
22.02.2016 / 21:36