LearningJrDev LearningJrDev - 7 months ago 43
Javascript Question

Jquery Index reporting wrong index

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

Answer

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.