1

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 line_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:)

1
  • I'm a little confused as to what you want. What you have looks perfectly fine to me if you want the index (0,1,2,3...) Commented Jul 26, 2011 at 4:09

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.