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:
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:
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.
J Query Related Interview Questions
|HTML 4 Interview Questions||HTML Interview Questions|
|HTML 5 Interview Questions||Zend Interview Questions|
|JqueryUI Interview Questions||Dynamic HTML Interview Questions|
|XQuery Interview Questions||jQuery Mobile Interview Questions|
J Query Related Practice Tests
|HTML 4 Practice Tests||HTML Practice Tests|
|HTML 5 Practice Tests||Zend Practice Tests|
|PHP and Jquery Practice Tests||J Query Practice Tests|
|CodeIgniter Practice Tests||Dynamic HTML Practice Tests|
J Query Tutorial
Selecting Elements With Jquery
Beyond The Basics
Faster, Simpler, More Fun
Html Form Enhancements From Scratch
Html Form Enhancements With Plugins
Interface Components From Scratch
User Interfaces With Jquery Ui
Jquery Ui Theming
Jquery, Ajax, Data Formats: Html, Xml, Json, Jsonp
Using Jquery In Large Projects
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.