Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append Query String to URL with Jquery

Tags:

jquery

What am I doing wrong?

  1. Only on pages with the URL location of "/MyWebsite/Example.aspx" append "?template=PW"
  2. But only to links that contain "/HelloWorld/default.aspx"

There is no ID or classes associated to this link, so I have to look for the URL.

This is my code, but the links are not updating.. I know I'm close!

$(document).ready(function(){
    if (document.location.href.indexOf('/MyWebsite/Example.aspx') > 0)  
        {
            $('a[href*="/HelloWorld/default.aspx"]').append("href",$("?template=PW"))
        }
});
like image 500
Evan Avatar asked May 06 '13 23:05

Evan


4 Answers

$(document).ready(function(){
    if (document.location.href.indexOf('/MyWebsite/Example.aspx') > 0)  
        {
            var $el = $('a[href*="/HelloWorld/default.aspx"]');
            $el.attr("href", $el.attr("href")+ "?template=PW");
        }
});
like image 98
Okan Kocyigit Avatar answered Sep 18 '22 13:09

Okan Kocyigit


Use $.attr() to edit an attribute.

$.append() is used to insert an html child node inside your element.

$(document).ready(function(){
    if (document.location.href.indexOf('/MyWebsite/Example.aspx') > 0)  
        {
            var href = '/HelloWorld/default.aspx';
            $('a[href*="' + href + '"]').attr("href", href + "?template=PW")
        }
});
like image 28
Flo Schild Avatar answered Sep 16 '22 13:09

Flo Schild


This would definitely solve your problem as it did mine.

<script type="text/javascript">
    var querystring = 'MyString'; // Replace this
    $('a').each(function(){
        var href = $(this).attr('href');
        href += (href.match(/\?/) ? '&' : '?') + querystring;
        $(this).attr('href', href);
    });
</script>
like image 40
shaz3e Avatar answered Sep 17 '22 13:09

shaz3e


Have you consider using PURL? With PURL I was able to do this:

var url = "http://localhost/some/url?item1=one&item2=two";
if ($.url(url).attr('query')) {
    url = url + '&newItem=new';
}
else {
    url = url + '?newItem=new';
}
like image 37
coderama Avatar answered Sep 20 '22 13:09

coderama