2

Html:

<!DOCTYPE html>
<html>
<head>
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
            <div id="radioButtonSet">
                <input type="radio" id="radio-value" name="dataChange" value="value" checked="checked" ><label for="radio-value">Value</label>
                <input type="radio" id="radio-percentage" name="dataChange" value="percent" ><label for="radio-percentage">Percentage</label>
            </div>
</body>
</html>

Javascript:

$("input[type=radio][name=dataChange]").on("change", function(){
  console.log($("input[type=radio][name=dataChange]").filter(":checked").index())
});

I expect the indices to be 0 and 1, but they are 0 and 2. Why?

Demo: http://jsbin.com/xifutarumu/edit?html,js,console,output

LearningJrDev
  • 911
  • 2
  • 8
  • 27

3 Answers3

2

From the docs: "If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements."

<div id="radioButtonSet">
    <input type="radio" id="radio-value" name="dataChange" value="value" checked="checked" >
    <label for="radio-value">Value</label>
    <input type="radio" id="radio-percentage" name="dataChange" value="percent" >
    <label for="radio-percentage">Percentage</label>
</div>

The radio-percentage input is the third of its siblings, and therefore has an index of two.

Hamms
  • 5,016
  • 21
  • 28
  • Ah, I was assuming sibling would be of the same filter type so only siblings that are `input[type=radio][name=dataChange]` – LearningJrDev Apr 27 '16 at 21:04
  • You can achieve that by doing something like `$("input[type=radio][name=dataChange]").index(':checked')`; consult the linked docs for more details – Hamms Apr 27 '16 at 21:06
  • For future googlers, the solution was `$("input[type=radio][name=dataChange]").index($("input[type=radio][name=dataChange]").filter(':checked'))` See http://stackoverflow.com/questions/5395537/jquery-how-to-get-the-index-of-a-checked-radio-button – LearningJrDev Apr 27 '16 at 21:14
  • or `$("input[type=radio][name=dataChange]").index(this)` – Hamms Apr 27 '16 at 21:16
1

Passing this as the context for index() seems to produce the desired results. shrug

$("input").index(this);

See http://jsbin.com/wuzoxocura/1/edit?html,js,console,output

Ozrix
  • 3,489
  • 2
  • 17
  • 27
0

It is showing correctly index as

0:first input

1:label just after 1 input

2:second input

Naresh Teli
  • 138
  • 1
  • 12