I am developing an option in Magento where the customer can enter multiple product ID's in a text box and add them to Shopping Cart. I have been able to do it for only one product ID where it is entered in a input box by using the following jquery,
$(document).ready(function(){
$("#submit").click(function(){
var id = $("#nam").val();
$.post("....../checkout/cart/add", { product:id },
function(data) {
alert("The Product is added to your shopping cart.");
window.location.reload(true);
});
});
});
var id fetches the value of the input box.
In an input box I am taking one product ID and so it's no problem in fetching the value and passing it to the add product page by using jquery.post(). But if I enter several product ID's separated by comma in a text box how will I fetch each productID and send it to add product page for updating ? Is there any better way to do it other than using jquery.post() method ?
You can split your Ids by a separator and iterate over the resulting array adding the items to the shopping card. Something like:
$(document).ready(function(){
$("#submit").click(function(){
var ids = $("#nam").val().split(' '); // SPACE seperated Ids
for(i = 0; i < ids.length; i++){
var id = ids[i];
$.post("....../checkout/cart/add", { product:id },
function(data) {
//alert("The Product is added to your shopping cart.");
//window.location.reload(true);
});
}
});
});
You will have to sanitize your textbox values before doing so.
$(document).ready(function () {
$("#submit").click(function () {
var productIds = [];
$.each($("#nam").val().split(','), function (i, value) {
if (value.length > 0) {
productIds.push(value);
}
});
$.post("....../checkout/cart/add", { productIds: productIds },
function (data) {
alert('The' + (productIds.length == 1 ? 'Product' : 'Products') + ' is added to your shopping cart.');
window.location.reload(true);
});
});
});
public ActionResult add(int[] productIds)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
you need to return array of product ids to post action then only it can be achieved.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.