Search code examples
jquerymodel-view-controllerreplacehrefcart

MVC jQuery it increases the quantity each time with .click function but doesnt replace the href at the same time


I have a product detail page. There are quantity up and quantity down buttons to change how many quantities will be added when the Add To Cart button is clicked.

Each time I click the "quantity up button" I want to change the href quantity so I can send the quantity info to the controller.

What is wrong here? Each time I click the quantity up button I get the correct increased quantity info like 2,3,4 etc. but each time I get /Home/AddToCart/1002?quantity=2 href info. ?quantity=2 should change like ?quantity=3 , ?quantity=4 etc.. but doesn't. What am I missing here?

$(".cart_quantity_up").click(function () {
        var val;
        var uri;
        var newuri;
        val = $(".cart_quantity_input").val();
        val++;
        uri = $("#addtocart").attr("href");
        newuri = uri.replace("xxxx", val);
        $("#addtocart").attr("href", newuri);
        $(".cart_quantity_input").val(val);
        alert(newuri);
});

xxxx represent a value to be changed later in jquery


Solution

    1. Use parseint
    2. Use prop instead of attr

      $(".cart_quantity_up").click(function () {
          var val;
          var uri;
          var newuri;
          val = parseInt($(".cart_quantity_input").val());
          val++;
          uri = $("#addtocart").prop("href");
          newuri = uri.replace("xxxx", val);
          $("#addtocart").prop("href", newuri);
          $(".cart_quantity_input").val(val);
          alert(newuri);
      });
      

    Remember, href will be change by this so xxxx will no longer be useable if you call this a second time!