remove radio checked input

Asked

Viewed 3,064 times

2

How can I remove checked input radio if a div has the click effect?

<!DOCTYPE html>
<html>
<body>

<form action="">
  <input type="radio" name="gender" value="male"> Male<br>
  <input type="radio" name="gender" value="female"> Female<br>
  <input type="radio" name="gender" value="other"> Other
</form>
 <div id="remover">
  <p>Remover checked de radio selecinado</p>
 </div>  
</body>
</html>

When the div with id "remove" has effect click remove checked input.

2 answers

3


This will solve your problem:

<div id="remover" onclick="$('input[name=gender]').prop('checked', false);">

Or:

$( "#remover" ).click(function() {
    $('input[name=gender]').prop('checked', false);
});

EDIT - Possibility to solve the problem with pure javascript:

<div id="remover" onclick="removerChecked();">

<script>
    function removerChecked() {
        var ele = document.getElementsByName("gender");
        for(var i=0;i<ele.length;i++){
           ele[i].checked = false;
        }
    }
</script>
  • That is if he has correct jQuery?

  • Correct, and among the tags of the question jQuery is marked.

  • I only commented because in the code he posted does not have the jQuary include, but if it is in the question tag is quiet.

  • No problem, I edited the answer to enable those who do not want jQuery also be helped in the future.

  • Very good, tmj!

2

You can reset the form (unchecking all) using .reset() with a simple code (if the form have only radio Buttons):

$("#remover").click(function(){
   $("form")[0].reset();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
  <input type="radio" name="gender" value="male"> Male<br>
  <input type="radio" name="gender" value="female"> Female<br>
  <input type="radio" name="gender" value="other"> Other
</form>
<div id="remover">
   <p>Remover checked de radio selecinado</p>
</div>

Or with pure Javascript:

document.querySelector("#remover").addEventListener("click", ()=>{
   document.querySelector("form").reset();
});
<form action="">
  <input type="radio" name="gender" value="male"> Male<br>
  <input type="radio" name="gender" value="female"> Female<br>
  <input type="radio" name="gender" value="other"> Other
</form>
<div id="remover">
   <p>Remover checked de radio selecinado</p>
</div>

  • The downside of this suggestion is that if it adds new fields to its form, this action will clear the form completely. And that might be inconvenient.

  • @Davidalves True. But the answer is based only on the scope of the question.

  • @Davidalves But your answer is well prepared, I’ll even give +1.

  • I understand. Yours is very good too. I just made a comment to anyone looking for this solution in the future to know the difference. But your answer is very useful if you want to clean the entire form.

Browser other questions tagged

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