Reputation: 1079
I am using Laravel 4.2. I have form inside a foreach
statement:
@foreach($result as $key => $prices)
$endforeach
Inside this foreach loop I have a form:
<div class="col-md-3 slide_content">
<div class="form-group">
<label for="">How many car?</label>
<select class="form-control" name="number_of_car" id="car_no">
<option value="" selected>select car numbers</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
</div>
<div class="col-md-3 slide_content">
<div class="form-group">
<label for="">Method to pay?</label>
<select class="form-control" name="payment_method" id="ad_tt">
<option value="">Select Type</option>
<option value="1">Full Payment</option>
<option value="2">Advance Payment</option>
</select>
</div>
</div>
Here is my Javascript code:
$(document).ready(function(){
$("#car_no").change(function(){
var number_of_car = $("#car_no option:selected").val();
var payment_type = $("#ad_tt option:selected").val();
var amount = "<?php $ad = $prices->totalAmount; echo 'Rs: '.$ad; ?>"; alert(amount);
});
});
My problem is, when I change the option value of rows other than first loop, I get the value of first row only. But, I need to get the from the respective row. So, How could I do that using jquery.
Any help would be appreciated. Thank you.
Upvotes: 1
Views: 1831
Reputation: 133433
IDs in HTML must be unique. This is expected behavior. Common classes can be used and use relationship to traverse the DOM using various methods.
Below I have used car_no
and ad_tt
as CSS class for select
element
HTML
<div class="col-md-3 slide_content">
<div class="form-group">
<label for="">How many car?</label>
<select class="form-control car_no" name="number_of_car" data-amount="<?php $ad = $prices->totalAmount; echo 'Rs: '.$ad; ?>">
</select>
</div>
</div>
<div class="col-md-3 slide_content">
<div class="form-group">
<label for="">Method to pay?</label>
<select class="form-control ad_tt" name="payment_method">
</select>
</div>
</div>
SCRIPT
$(document).ready(function(){
$(".car_no").change(function(){
var number_of_car = $(this).val();
var payment_type = $(this).closest('.slide_content').next('.slide_content').find(".ad_tt" ).val();
var amount = $(this).data("amount");
alert(amount);
});
});
Upvotes: 1
Reputation: 4246
You cannot use id for more than one element. You have to use class.
<select class="form-control" name="number_of_car" class="car_no" >
and
var number_of_car = $(this).val();
similarly get the value for the other dropdown.
Upvotes: 1
Reputation: 4749
You have to use class instead of id since the id must be unique in DOM. Here you are triggering the change event for id = car_no, that you have to make unique by appending iterator value to the id.
$("#car_no").change(function() {} //should replace with
$(".car_no").change(function(){
// use $(this).attr('data') to identify the element.
}
Upvotes: 1