How to get index value from jquery .each() function
I'm having trouble fetching the index of another field from jquery .each() function. I want to fetch the value of the input with the name line_id[] :
$('input[name=bl_caps[]]').each(function(index){
var l开发者_运维知识库ine_id = $('input[name=line_id[]]').val();
var caps = $(this).val();
alert('line id: ' + line_id + '<br/>' + 'caps: ' + caps);
});
HTML:
<?php foreach(){ ?>
<input type="hidden" name="line_id[]" id="line_id" value="<?php echo $sbl->BusLineID; ?>"/>
<td><input type="text" name="bl_caps[]" id="bl_caps"/></td>
<?php } ?>
I'm planning to do it like this:
var line_id = new Array();
$('input[name=line_id[]]').each(function(index){
line_id[index] = $(this).val();
});
$('input[name=bl_caps[]]').each(function(index){
var line_ids = line_id[index];
var caps = $(this).val();
alert('line id: ' + line_ids + '<br/>' + 'caps: ' + caps);
});
But I'm hoping that I could find a better answer here:)
I think the easiest way to to do what you're trying to do is to use the .prev() function:
$('input[name=bl_caps[]]').each(function(){
// get the previous sibling
var line_ids = $(this).prev().val();
var caps = $(this).val();
alert('line id: ' + line_ids + '<br/>' + 'caps: ' + caps);
});
Note that this only works if you put the hidden input inside the td
element, which is where it should be anyway:
<?php foreach(){ ?>
<td>
<input type="hidden" name="line_id[]" id="line_id" value="<?php echo $sbl->BusLineID; ?>"/>
<input type="text" name="bl_caps[]" id="bl_caps"/>
</td>
<?php } ?>
For mapping values to an array, you might try the .map() function:
var line_ids = $('input[name=line_id[]]').map(function(){
return $(this).val();
}).toArray();
Note that it gives you a jQuery object, not a true array, hence the .toArray()
call at the end.
精彩评论