I’m using this customInput plugin (with jQuery 1.6.2) to customize the look of my radio buttons.
It works great.
The problem I have now is that I’m just trying to get the index() number of the selected radio button and it always returns 0. There are six radio buttons and I’m looking for a number between 0 and 5.
JavaScript:
$('input[name="amount"]').click(function() {
var x = $(this).filter(':checked').index();
var y = $(this).filter(':checked').val(); //<-- for troubleshooting
alert(x + y); //<-- for troubleshooting
});
Oddly, val() is still working fine and returns the proper value. Therefore, the form data is always getting the correct radio value.
http://jsfiddle.net/sparky672/LdVGD/
HTML:
<fieldset id="radioset">
<input type="radio" id="radio-1" name="amount" value="Option 1" checked="checked" /><label for="radio-1" title="">Option 1</label>
<input type="radio" id="radio-2" name="amount" value="Option 2" /><label for="radio-2" title="">Option 2</label>
<input type="radio" id="radio-3" name="amount" value="Option 3" /><label for="radio-3" title="">Option 3</label>
<input type="radio" id="radio-4" name="amount" value="Option 4" /><label for="radio-4" title="">Option 4</label>
<input type="radio" id="radio-5" name="amount" value="Option 5" /><label for="radio-5" title="">Option 5</label>
<input type="radio" id="radio-6" name="amount" value="Option 6" /><label for="radio-6" title="">Option 6</label>
</fieldset>
When simply not using the customInput plugin, the index number is then returned.
http://jsfiddle.net/sparky672/LdVGD/1/
Side Question:
After disabling the plugin, the index() returns 0, 2, 4, 6, 8, or 10. It’s like the <label> itself is being counted at part of the index(), effectively doubling the count. Why should this be?
I cannot remove the <label> elements as the plugin depends on these to function.
I just want to retrieve a number from 0 to 5 depending on whether radio button 0 through 5 is checked.
Any suggestions? Perhaps another method to check which radio button is selected?
My ultimate goal? To simply change some variables depending on which button is selected.
As you’ve noticed, your
indexcall doesn’t quite work the way you expect it to when you don’t use the plugin. From the fine manual:You’re getting values twice as large as you think they should be because the
<label>elements are also siblings so you have five<input>elements and five<label>elements in the sibling list.When you activate the plugin, your radio buttons get wrapped in a
<div>so the structure of each button looks like this:That leaves the radio button with a single sibling,
<label>, and anindexof zero.You already have
idattributes on your radio buttons so why not use those to figure out the index? Something like this:Check the third number in these demos:
Or you could use the element form of
index:So you could do it like this:
And some demos: