无法从jquery中的输入字段获取值

时间:2017-05-07 00:03:32

标签: php jquery ajax laravel

我有这个输入

@foreach($products as $product)
<div class="form-group">
<input type="number" value=""  min="1" max="100" id="{{ $product>product_id }}-qty" class="form-control {{ $product->product_id }}-qty">
</div>
<div class="form-group">
<textarea class="form-control" name="comment" id="{{ $product->product_id }}-comment" ></textarea>
</div>
<button class="btn" onclick="addToCart({{ $product->product_id }})">
 <i class="fa fa-shopping-cart"></i> Add to Cart</button>

@endforeach

和这个javascript函数

function addToCart(productID){
    //alert(document.getElementById(productID+"-qty").value)
    var comment=jQuery("#"+productID+"-comment").val();
    alert(comment)
}

总是返回空字符串。

2 个答案:

答案 0 :(得分:0)

试试这个:

function addToCart(productID){
    //alert(document.getElementById(productID+"-qty").value)
    var comment=jQuery("#"+productID+"-comment").val();
    alert(comment)
}

你变空了,因为没有id =“27-product_slug”的元素

答案 1 :(得分:0)

当您在按钮上单击时使用功能时,您可以从此按钮开始

在js

function addToCart(el){
    var input_value = jQuery(el).prev('.form-group').prev('.form-group').find("input").val();
    var comment=jQuery(el).prev('.form-group').find("textarea").val();
    alert(comment)
}

in html

<button class="btn" onclick="addToCart(this)">
  

注意:最好将代码包装在div中并使用   .closest().find()代替使用.prev()

相关问题