Romes Romes - 1 year ago 123
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

$("#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
, and then checks checkbox B

User decided to uncheck checkbox A. The code removes the
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 Source

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

$(".url_p").change(function() {
  var href = "";
  $(".url_p").each(function(i) {
    if (!$(this).is(":checked")) return;
    href += (href.indexOf("?")==-1 ? "?" : "&") + + "=" + encodeURIComponent($(this).val());
  $("#buynow").attr("href", href);
<script src=""></script>
<input type='checkbox' class='url_p' name='product_id' value='100'>Product id

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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download