1

I have a group of 4 radio buttons followed by a text input, when users click on the text input field I am trying to clear all radio inputs. here is my code so far.

 <input type="radio" name="radio"><label for="radio1">1</label>
 <input type="radio" name="radio"><label for="radio2">2</label>
 <input type="radio" name="radio"><label for="radio3">3</label>
 <input type="radio" name="radio"><label for="radio4">4</label>
 <input type="text" id="textInput">

 <script>
      $('#textinput').click(function () {
          radio.checked = false;
      });
 </script>
Jonas
  • 121,568
  • 97
  • 310
  • 388
nick
  • 1,226
  • 3
  • 21
  • 38

4 Answers4

6

You can use .prop() to set checked property of input rabio buttons. Also you have misspelled textInput while event binding

<script>
      $('#textInput').click(function () {
          $('input[name="radio"]').prop("checked", false);
      });
 </script>

DEMO

Satpal
  • 132,252
  • 13
  • 159
  • 168
2
<script>
      $('#textInput').click(function () {
          $('input[type=radio]').removeAttr("checked");

      });
 </script>
Irfan TahirKheli
  • 3,652
  • 1
  • 22
  • 36
  • The id should be "textInput" not "textinput" (capital I). – Organiccat Feb 03 '14 at 20:42
  • @user3117555 don't give same name to all radio buttons. name should be a unique for each element –  Feb 03 '14 at 20:43
  • 1
    If you need to group you radio buttons then you need to give it same name. Otherwise you will be able to select all of them at a time. @i_m_optional – Irfan TahirKheli Feb 03 '14 at 20:46
  • but if you want to select them indivisually then different name comes handy. –  Feb 03 '14 at 20:47
  • Yes but radio button are meant to select only one option at a time :) – Irfan TahirKheli Feb 03 '14 at 20:47
  • @i_m_optional, OP is using radio button thus to define group You have to use same name and I agree radio button are meant to select only one option at a time – Satpal Feb 03 '14 at 20:50
1

Or you can try attr() method

 $('#textInput').click(function () {
         $('input[name="radio"]').attr('checked',false);

      });

DEMO

1

I think the best way to modify your script block (without changing your html) is first by ensuring that the code runs on document ready, and also you should probably ensure that the event is focus, not click, in case someone is using a keyboard or alternate navigation:

$(function() {
    $('#textInput').focus(function () {
          $('input[name=radio]').prop("checked", false);
    });
});

Though it's probably more likely that you want to only clear other selections if they actually enter some data in that field, you might want to instead do:

$(function() {    
    $('#textInput').on('input', function () {
        if($(this).val().length > 0) {
            $('input[name=radio]').prop("checked", false);
        }
    });
});
Rick Dailey
  • 130
  • 5