我有2个输入,如下所示。其中1个是按钮,另一个是文本框。 qty-input用于输入产品的数量,当我使用jquery单击按钮时。我更新了购物车。当我将其硬编码为1时,它可以正常工作,但我无法通过从文本框中读取而无需回发来弄清楚如何操作。
以下代码属于partialview中的1个产品,它显示在列表中,我需要为每个创建的文本框分配id,因此,此文本框应属于按钮。
当我只使用var quantity = $('.qty-input').val();
时,它仅适用于第一个生成的文本框。这意味着如果我想将第二个产品添加到购物车中,它会因为它具有相同的类而混淆。因此我必须与Id合作。
另一个想法可以使用angular.js,我看到一些例子,看起来很容易实现它,但我无法弄清楚如何做到这一点?
jquery或angular.js,我需要你的帮助。感谢。
在我的部分视图中
var quantity = 1;
string addtocartlink = "";
addtocartlink = Url.RouteUrl("AddProductToCart-Catalog", new { productId = Model.Id, shoppingCartTypeId = shoppingCartTypeId, quantity = quantity });
<div class="cart-input">
<input class="qty-input" id="@Model.Id" data-val="true" type="text" value="1">
<input type="button" value="@(addToCartClass)" class="button-2 product-box-add-to-cart-button @addToCartClass" onclick="AjaxCart.addproducttocart_catalog('@addtocartlink');return false;" />
</div>
我的javascript
addproducttocart_catalog: function (urladd,id) {
if (this.loadWaiting != false) {
return;
}
this.setLoadWaiting(true);
var quantity = $(id).val();
urladd = urladd.substring(0, urladd.length - 1) + quantity;
$.ajax({
cache: false,
url: urladd,
type: 'post',
success: this.success_process,
complete: this.resetLoadWaiting,
error: this.ajaxFailure
});
},
答案 0 :(得分:2)
有两种方法可以实现它。
一个。要获取id,您只需在javascript中声明一个变量:
var id = '@Model.Id';
湾您可以为输入元素指定属性。
<input class="qty-input" id="@Model.Id" data-val="true" type="text" unique-id="qty" value="1">
var id = $("input[unique-id='qty']").attr("id");
答案 1 :(得分:1)
根据您的评论,您有Quantity
的多个文本框输入和相关按钮。您可以使用相对选择器来处理此问题,并且无需添加任何id
属性。将您的HTML更改为
<div class="cart-input">
<input class="qty-input" type="text" value="1">
<input type="button" value="Add to cart" class="button-2 product-box-add-to-cart-button @addToCartClass" data-id="@Model.Id" />
</div>
请注意,productID值已添加为按钮中的data
属性。然后脚本将是
var url = '@Url.RouteUrl("AddProductToCart-Catalog")';
$('.product-box-add-to-cart-button').click(function() {
var id = $(this).data('id');
var qty = $(this).closest('.cart-input').find('.qty-input').val();
$.ajax({
cache: false,
url: url,
type: 'post',
data: { productId: id, shoppingCartTypeId: shoppingCartTypeId, quantity: qty },
success: this.success_process,
....
});
});
附注:我从文本框中删除了data-val="true"
。只有在视图中有一个您似乎没有的关联ValidationMessageFor()
时才有意义,而且无论如何它仍然允许您输入显然会失败的"ABC"
,而您甚至无法检查如果在发布之前有效。您应该停止使用手动html和partials,并为模型使用EditorTemplate
(模型包含属性int Quantity
),并使用强类型HtmlHelpers生成视图。然后你可以使用.Valid()
方法在发布之前检查数量是否有效(如果没有则取消它)