Search code examples
javascriptjqueryhtmlreplacehref

Trying to dynamically replace a url &option value based on <input> button


I'm trying to dynamically replace a url value, i'm using replace because i don't want the value to be duplicated on every click

I'm certainly not the best coder in the world, and i'm not sure if my syntax is valid or not.

The general idea i'm trying to accomplish below is there are several urls on the page, only one is shown at any given time i use a slider to hide/show each url in a seamless manner.

I want to pass a location to the javascript function (it will be a number) and that function should take the location number and replace the section in all href="" on the page.

But i can't seem to get it to work.

function getlocation(loc) {
  $('a').each(function() {
    var location = $(this).attr('href');
    $(this).attr('href').replace("&location=100", "&location=loc");
    console.log('error');
  });
}
<a class="button" href="#get.php&location=100">Test</a>
<br>
<br>

<a class="button" href="#get.php&location=100">Test</a>
<br>
<br>


<feildset>
  <input id="mtl" name="location" type="radio" checked>
  <label for="mtl" onclick="getlocation(mtl)">Montreal</label>
  <br>
  <br>
  <input id="frkfrt" name="location" type="radio" onclick="">
  <label for="frkfrt" onclick="getlocation(frkfrt)">Frankfurt</label>



</feildset>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>


Solution

    • frkfrt and mtl are not variables - you want to pass it as a string. But inline event handlers are as bad as eval inside HTML - attach the handler properly using Javascript instead, to make problems like these less likely.
    • replace does not mutate the original string - strings are immutable. Instead, you need to explicitly assign to the hrefs in order to change them.
    • In getlocation, you have to concatenate the loc variable with the &location=

    ['mtl', 'frkfrt'].forEach(loc => {
      document.querySelector(`[for="${loc}"]`).onclick = () => getlocation(loc);
    });
    
    
    function getlocation(loc) {
      document.querySelectorAll('a').forEach(a => {
        a.href = a.href.replace(/&location=.*$/, "&location=" + loc);
      });
    }
    <a class="button" href="#get.php&location=100">Test</a>
    <br>
    <br>
    
    <a class="button" href="#get.php&location=100">Test</a>
    <br>
    <br>
    
    
    <feildset>
      <input id="mtl" name="location" type="radio" checked>
      <label for="mtl">Montreal</label>
      <br>
      <br>
      <input id="frkfrt" name="location" type="radio">
      <label for="frkfrt">Frankfurt</label>
    
    
    
    </feildset>