Who is going to win the Heineken cup next year?
Who is going to win the Heineken cup next year?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<script type="text/JavaScript" | |
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"> | |
</script> | |
</head> | |
<body> | |
Consider a form as such: | |
<p>Who is going to win the Heineken cup next year?</P> | |
<ul id="choice"> | |
<li> | |
<input name="source" id="source1" type="radio" value="Leinster"/> | |
<label for="source1">Leinster</label> | |
</li> | |
<li> | |
<input name="source" id="source2" type="radio" value="Munster"/> | |
<label for="source2">Munster</label> | |
</li> | |
<li> | |
<input name="source" id="source3" type="radio" value="Ulster"/> | |
<label for="source3">Ulster</label> | |
</li> | |
<li> | |
<input name="source" id="source4" type="radio" value="Connacht"/> | |
<label for="source4">Connacht</label> | |
</li> | |
<li> | |
<input name="source" id="source5" type="radio" value="Other"/> | |
<label for="source5">Other</label> | |
<input name="Source5Txt" id="Source5Txt" type="text"/> | |
</li> | |
</li> | |
</ul> | |
<script> | |
$('#choice input:text').(function() { | |
// store some variables locally as they are used more than once. | |
var $inputText = $(this); | |
var $radioBtn = $inputText.siblings('input:radio'); // all sibling radio buttons | |
// If any of the sibling radio buttons change, check to see | |
$radioBtn.change(function(){ | |
// if it checked focus on the text input | |
if (this.checked) {$inputText.focus();} | |
}); | |
// listen for events on the text input | |
$inputText.keypress(function() { | |
$radioBtn.attr('checked', true); | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
- :text is a JQuery psuedo class Selector which selects all elements of type text. As per JQuery recommendations, pseudo class Selectors should be preceded with another selector or tag element otherwise the universal selector is implied. In this case we do input:text and only one text box will be selected. That's ok.
- The .each(function(){ means iterate overall inputs of type text and execute the specified function. Don't forget ".each" can operate on sets of elements of any size including just 1 which is the case in this example.
- $(this) corresponds to the object which is being operated on by each. In this case it is each input text box. If you don't believe me add:
console.log("this is: " + $(this)[0].id);
and you will see something like:
this is: Source5Txt in the console.
- The inputText button and radio button are stored in the local context. This is for efficiency.