Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add variable to end of href URL onClick JQUERY

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>
like image 396
916 Networks Avatar asked Mar 27 '13 05:03

916 Networks


3 Answers

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';
    });
}
like image 119
Christophe Avatar answered Nov 09 '22 09:11

Christophe


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>
like image 40
luchosrock Avatar answered Nov 09 '22 07:11

luchosrock


     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'
           }
like image 2
Nirmal Avatar answered Nov 09 '22 08:11

Nirmal