Romes Romes - 1 month ago 5
Javascript Question

Remove lastIndexOf url with checkboxes

I'm trying to create a 2checkout buy now button. In order to get the correct products into the cart, you need to pass product ID's into the URL. I'm trying to build the URL based on how the user checks and unchecks checkboxes.

For example:



When the user checks a checkbox, a URL parameter is added to the base URL using
&product_id=


$("#buynow").attr('href', function(){
var baseURL = this.href;
var newURL = baseURL + '&product_id=' + productID;
return newURL;
})


The user unchecks the checkbox, therefore, removing the product ID from the URL:

$("#buynow").attr('href', function(){
var oldURL = this.href;
var newURL = oldURL.substr(oldURL.lastIndexOf('&'));
return url.replace( new RegExp(oldURL), '' );
})


The problem I'm having is that I have multiple checkboxes that add and remove to the URL.

Typical scenerio:



User checks checkbox A
product_id=1
, and then checks checkbox B
product_id1=2
.

http://baseurl.com/sid=12345&product_id=1&product_id1=2


User decided to uncheck checkbox A. The code removes the
lastIndexOf
based on '&' which then removes checkbox B product ID.

How can I write the code such that it removes not just the last parameter added to the URL, however, it knows which product to remove based on the ID of the product.

Hope this makes sense.

Answer

Here is a simple example to update href based on checkbox's name and value.

$(".url_p").change(function() {
  var href = "http://baseurl.com/";
  $(".url_p").each(function(i) {
    if (!$(this).is(":checked")) return;
    href += (href.indexOf("?")==-1 ? "?" : "&") + this.name + "=" + encodeURIComponent($(this).val());
  });
  console.log(href);
  $("#buynow").attr("href", href);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='checkbox' class='url_p' name='product_id' value='100'>Product id
<br/>

<input type='checkbox' class='url_p' name='price' value='80'>Price
<br/>

<input type='checkbox' class='url_p' name='amount' value='1'>Amount
<br/>

<a id='buynow' href='#'>Buy Now</a>