There is a form:

<form> <div id='type'> <input type='radio' id='radio_1' name='type' value='1' /> <input type='radio' id='radio_2' name='type' value='2' /> <input type='radio' id='radio_3' name='type' value='3' /> </div> </form> 

How in jQuery or JavaScript to make so that when you click on a radio button, the <input> attribute is set to "checked="checked" ? As with the rest of the previously selected, this attribute should disappear. Ie, the selected button should always be present "checked="checked" .

For example, we selected the button with id='radio1' , it should have the checked attribute. After that we decided to choose another button with id='radio2' . After clicking on radio2 , the ckecked attribute appears to ckecked , and for id='radio1' this attribute disappears. And so on for all radio switches.

  • it is already installed in the described way, if they have the same name attribute specified by means of css - lexxl
  • @lexxl It is necessary to set the input to iron, so that it can be seen through the console - Pavel
  • through the console will be visible. you can check this by <input type='radio' id='radio_1' name='type' value='1' checked /> || $('#radio_1').prop('checked') - lexxl
  • @lexxl Could you write an example in response? - Pavel

1 answer 1

The described functionality is implemented by native CSS means by specifying the same name attribute for the desired radio buttons.

If there is a need to implement a similar behavior for checkbox-elements (or still you need to additionally be hardcoded through jQuery ), the following code will help:

 $(function(){ $('input').click(function(){ $('input').each(function(){ $(this).prop('checked', false); }); $(this).prop('checked', true); }); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form> <div id='type'> <input type='checkbox' id='radio_1' name='type' value='1' /> <input type='checkbox' id='radio_2' name='type' value='2' /> <input type='checkbox' id='radio_3' name='type' value='3' /> </div> </form> 

You can check for the presence of the checked property as follows:

 $('#radio_1').prop(‌​'checked') 

If there is a property in the console, it will display true , if it is false .

  • You can check for the presence of the checked attribute in the following way: - here it is not - then the presence of the property is checked here, the attribute may be absent - Grundy
  • @lexxl Thanks for the reply! And in Elements in Chrome, the value of the element does not change - Pavel
  • @Pavel, why do we need it to change? - Grundy
  • @Grundy Need to get the value of the currently selected switch. Then send the value via Ajax server. - Pavel
  • one
    @Pavel, because, sometimes it can lead to unexpected results. In addition, there is nothing about the library version in the question, and since the behavior and functions vary greatly depending on the version, it is generally accepted that this is the latest stable version. - Grundy