Reputation: 1286
I'm using jquery sortable on div containing a number of section elements. I would like to use index() to output position of each section.
index() only returns value for the first section but it can't locate the second one (or third, fourth etc.)
I can't figure out what am I doing wrong. Any help would be appreciated. Here's my code:
<div id="existingquestions" class="sortable">
<section class="question" id="question_777">
<p id="positionof_777"></p>
<p class="questiontext">question.text</p>
<script>$(document).ready(function() {
var qpos = Number($('.sortable > section:visible').index('#question_777')+1);
$('#positionof_777').html(qpos);
});
</script>
</section>
<section class="question" id="question_888">
<p id="positionof_888"></p>
<p class="questiontext">question.text</p>
<script>$(document).ready(function() {
var qpos = Number($('.sortable > section:visible').index('#question_888')+1);
$('#positionof_888').html(qpos);
});
</script>
</section>
</div>
The other function that I'm using works just fine although it's basically the same as above:
$(document).ready(function() {
$('input').placeholder();
$(".sortable > section:visible").hover(function() {
var index = $(this).index()+1;
$("#example_index").html("Index " + index);
});
});
I'm clueless. What am I doing wrong in the first example?
Upvotes: 2
Views: 146
Reputation: 87073
This will work as you desired:
<div id="existingquestions" class="sortable">
<section class="question" id="question_777">
<p id="positionof_777"></p>
<p class="questiontext">question.text</p>
<script>
$(document).ready(function() {
var qpos = $('.sortable > section:visible#question_777').index() + 1;
$('#positionof_777').html(qpos);
});
</script>
</section>
<section class="question" id="question_888">
<p id="positionof_888"></p>
<p class="questiontext">question.text</p>
<script>
$(document).ready(function() {
var qpos = $('.sortable > section:visible#question_888').index() +1 ;
$('#positionof_888').html(qpos);
});
</script>
</section>
</div>
You don't need Number
to conversion, .index()
always return a number.
Upvotes: 1