0

Input with value:

<input type="text" id="quantity" value="1" size="2"/>

ActionLink replaced with Url.Action:

<a href="@Url.Action("AddToCart", "Shop", new {parts_id=@Model.Parts.parts_id, quantity = "xxx"})" id="lnk">To cart</a>

and JS where I'm trying to replace the value:

 <script>
 $("#lnk").click(function (evt) {
     var fakeUri = $("#lnk").prop("href");
     var uri = fakeUri.replaceWith("xxx", $("#quantity").val());
     uri = $("#lnk").prop("href", uri);
 });
</script>

I think problem is in JS, the value is not replacing, client side sends "xxx"

C. America
  • 87
  • 1
  • 2
  • 10

2 Answers2

0

This should work

One of the problems what your href="@Url.Action("AddToCart"

It would return a href that looked like @Url.Action("addToCart" and nothing more. becuase of the "

Or you can do this <a href="@(Url.Action("AddToCart", "Shop ", new {parts_id=@Model.Parts.parts_id, quantity = "xxx "}))">

^Add () around the url

$("#lnk").click(function(event) {
  event.preventDefault();
  var fakeUri = $("#lnk").attr("href");
  var uri = fakeUri.replace("xxx", $("#quantity").val());
  uri = $("#lnk").attr("href", uri);
  window.location = uri;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="quantity" value="1" size="2" />

<a href='@Url.Action("AddToCart", "Shop ", new {parts_id=@Model.Parts.parts_id, quantity = "xxx "})' id="lnk">To cart</a>
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
0

Let's try different way of doing it, First we add event listener for quantity change, everytime it happens, we replace the href attribute value, notice that we should use attr not prop something like this

<a href="#" id="lnk">To cart</a>

js

$(document).on("change","#quantity",function () {
   var qnty = $("#quantity").val();
  var theuri = "@Url.Action("AddToCart", "Shop")?parts_id=@Model.Parts.parts_id&quantity="+qnty;
 $("#lnk").attr("href", theuri);
});
Munzer
  • 2,216
  • 2
  • 18
  • 25