17

I feel like this should work, but doesn't. Not sure what I'm doing wrong.

function addURL()
{   
$(this).attr('href', function() {
return this.href + '&cylnders=12';
}   


<a onclick="addURL();" href="/search-results/?var1=red&var2=leather">Click this</a>

3 Answers 3

32

First, you are missing a bunch of brackets:

function addURL()
{
    $(this).attr('href', function() {
        return this.href + '&cylnders=12';
    });
}

Second, in your code "this" refers to the window, not the element. Try this instead:

<a onclick="addURL(this)" href="/search-results/?var1=red&var2=leather">Click this</a>

function addURL(element)
{
    $(element).attr('href', function() {
        return this.href + '&cylnders=12';
    });
}
Sign up to request clarification or add additional context in comments.

4 Comments

Ah, good catch, thank you. Unfortuantely that didn't quite fix it, though syxtax error for sure.
For the record you don't need jQuery: function addURL(element){element.href+='&cylnders=12';}
Does JQUERY have more overhead and potential for issues, while the javascript is much more simple and less potential for trouble?
jQuery is not small, if you are just using it for this purpose it's a significant overhead. More potential for issues: no.
4

Why don't you add an ID or Class to your link href to identify it through jquery? It seems like your link is triggered before you can add any data to href attribute.

<a class="datalink" href="/search-results/?var1=red&var2=leather">Click this</a>
<script>

$('.datalink').attr('href', function() {
return this.href + '&cylnders=12';

});

</script>

1 Comment

Hi, since there is no javascript function defined for anchor tag in your example, 'return' statement won't work. Instead it should be "this.href = this.href + '&cylnders=12"
2
     function addURL()
      {
     var data=window.location+"&cylnders=12";
     alert(data);
     }

Try this concept. hope it will give you some solution.

Try this too

          function addURL()
          {
               window.location.href='/search-results/?var1=red&var2=leather&cylnders=12'
           }

1 Comment

When I add this, I click the link and it returns my current URL with the variable appended. I guess what I'm trying to do is grab the URL in the href, add the varibale to the end, and then go to that URL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.