我有一些输入字段具有相同的类,它们是由ajax请求动态生成的。当我尝试获取第二或第三输入字段的值时,我正在获取第一输入字段的值。
HTML:
<input type="number" name="product_quantity" class="form-control Product_quantity" value="11"/>
<input type="button" onclick="updateQuantity(41)" class="btn btn-primary" value="Update">
<input type="number" name="product_quantity" class="form-control Product_quantity" value="9"/>
<input type="button" onclick="updateQuantity(42)" class="btn btn-primary" value="Update">
<input type="number" name="product_quantity" class="form-control Product_quantity" value="5"/>
<input type="button" onclick="updateQuantity(43)" class="btn btn-primary" value="Update">
JS:
function updateQuantity(id){
var url = "{{ url('/api/carts/update') }}";
var product_quantity = $('.product_quantity').val();
var cart_id = id;
$.post(
url,
{
product_quantity: product_quantity,
id:cart_id
}
).done(function(data){
data = JSON.parse(data);
if(data.status == "success"){
alertify.set('notifier','position', 'top-center');
alertify.success('Item updated successfully !!');
$("#totalItems").html(data.totalItems);
}
});
答案 0 :(得分:0)
alert(document.getElementsByClassName("Product_quantity")[0].value);
alert(document.getElementsByClassName("Product_quantity")[1].value);
alert(document.getElementsByClassName("Product_quantity")[2].value);
<input type="number" name="product_quantity" class="form-control Product_quantity" value="11"/>
<input type="button" onclick="updateQuantity(41)" class="btn btn-primary" value="Update">
<input type="number" name="product_quantity" class="form-control Product_quantity" value="9"/>
<input type="button" onclick="updateQuantity(42)" class="btn btn-primary" value="Update">
<input type="number" name="product_quantity" class="form-control Product_quantity" value="5"/>
<input type="button" onclick="updateQuantity(43)" class="btn btn-primary" value="Update">
答案 1 :(得分:0)
function updateQuantity(id){
var url = "{{ url('/api/carts/update') }}";
var product_quantity = $('#product_quantity'+id).val();
alert(product_quantity);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<!-- You should give id for each input types like below -->
<input type="number" name="product_quantity" id="product_quantity41" class="form-control Product_quantity" value="11"/>
<input type="button" onclick="updateQuantity(41)" class="btn btn-primary" value="Update">
<input type="number" name="product_quantity" id="product_quantity42" class="form-control Product_quantity" value="9"/>
<input type="button" onclick="updateQuantity(42)" class="btn btn-primary" value="Update">
<input type="number" name="product_quantity" id="product_quantity43" class="form-control Product_quantity" value="5"/>
<input type="button" onclick="updateQuantity(43)" class="btn btn-primary" value="Update">