Selecting Radio Buttons Automatically - J Query

You have a series of radio buttons. The last radio button is labeled “Other” and has a text input field associated with it. Naturally you’d want that radio button to be selected if the user has entered text in the Other field:

Solution 1

In the HTML code you’ll notice the radio button, label, and associated text input elements are wrapped in an <li>tag. You don’t necessarily need this structure, but it makes finding the correct radio button much easier—you’re guaranteed there’s only one radio button sibling:

Solution 2

To take the concept one step further, when the radio button is selected, we can .focus() the text field. It’s important to note that the following code completely replaces the previous solution. Instead of using the .blur() method and then chaininga .each() method, just use the .each() method since that gives us access to all the objects we need:


The jQuery .sibling() method only returns siblings, not the HTML element you’re attempting to find siblings of. So, the code $(this).siblings('input:radio') could be rewritten $(this).siblings('input') because there is only one other input that is asibling. I prefer including the :radio selector because it is more explicit and creates self commenting code.
It would have been very easy to target the Other text input directly using $('#source5txt').focus(...) and have it directly target the radio button using its id attribute. While that’s a perfectly functional approach, the code as shown previously is more flexible. What if someone decided to change the id of the Other radio button? What if each radio button had a text input? The abstract solution handles these cases without additional work.
Why use .blur() instead of .focus() on the text input? While .focus() would be more immediate for selecting the associated radio button, if the user were simply tabbing through the form elements, .focus() would accidentally select the radio button. Using.blur() and then checking for a value avoids this problem.
What will happen when JavaScript is disabled? The user will have to manually click into the text input to start typing and manually select the radio button. You are left to decide how to validate and process submitted data should the user enter text and select a different radio button.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics