开发者

Javascript replace method not functioning in checkbox if/else toggle

开发者 https://www.devze.com 2023-03-31 06:07 出处:网络
I have a bit of Javascript I\'m playing with, which is called by a number of checkboxes and will ideally perform an action (adding and removing &attributeValue=attribID to the URL cumulatively) up

I have a bit of Javascript I'm playing with, which is called by a number of checkboxes and will ideally perform an action (adding and removing &attributeValue=attribID to the URL cumulatively) upon the checkbox being checked/unchecked.

Here's the Javascript:

var filterBaseURL = <?="\"".$url."\""?>; /*This is just copying a php variable that contains the base URL defined earlier - all of this works fine*/
var filterFullURL = filterBaseURL;
function filterToggle(attribID)
{
  var elementII = document.getElementById(attribID);
  if(elementII.checked){
     filterFullURL = filterFullURL+"&attributeValue="+attribID;
  }
  else {
     filterFullURL.replace("&attributeValue="+attribID, "");
     alert(filterFullURL);
  }
}

So what I'm doing here is attempting to on check of a checkbox add that checkbox's attributeValue to the URL, and on uncheck of a checkbox, remove that checkbox's attributeValue from the URL. I am using the filterFullURL = filterFullURL+"..." because there are multiple checkboxes and I want all their attributeValues to cumulatively be added to the URL.

All of this is working fine - the only thing that isn't working fine is the else statement action -

filterFullURL.replace("&attributeValue="+attribID, "");

Here are some example checkboxes:

<input type="checkbox" onclick="filterToggle('price_range_0_20')" name="Price_Range" value="Below_$20" id="price_range_0_20" /> Below $20
<input type="checkbox" onclick="filterToggle('price_range_20_40')" na开发者_如何转开发me="Price_Range" value="$20_-_$40" id="price_range_20_40" /> $20 - $40
<input type="checkbox" onclick="filterToggle('price_range_40_70')" name="Price_Range" value="$40_-_$70" id="price_range_40_70" /> $40 - $70

So to recap - I can add the attributeValues of all the checkboxes together, but I can't delete any of them. Any help here? Thanks!


Do you not need to save the output of filterFullURL.replace like filterFullURL = filterFullURL.replace("&attributeValue="+attribID, "")?


There was also an alert missing from the if statement - not sure if that's intentional, but this should operate well for you:

var filterBaseURL = <?="\"".$url."\""?>; /*This is just copying a php variable that contains the base URL defined earlier - all of this works fine*/
var filterFullURL = filterBaseURL;
function filterToggle(attribID)
{
  var elementII = document.getElementById(attribID);
  if(elementII.checked){
     filterFullURL = filterFullURL+"&attributeValue="+attribID;
     alert(filterFullURL);
  }
  else {
     filterFullURL = filterFullURL.replace("&attributeValue="+attribID, "");
     alert(filterFullURL);
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消