Sachin Kainth
Sachin Kainth

Reputation: 46740

Update anchor using JavaScript

I have a page with a table. The table contains th elements, which contain anchors. This is what an example th looks like:

<th scope="col">
<a href="/Admin/Auction/Closed?sort=InventoryReference&sordir=ASC&sortdir=DESC">Inventory reference</a>
</th>

What I want to do is update the anchor so that it has an extra query string parameter thus:

<th scope="col">
<a href="/Admin/Auction/Closed?sort=InventoryReference&sordir=ASC&sortdir=DESC&page=3">Inventory reference</a>
</th>

Now, I now that I must do this:

<script language="javascript" type="text/javascript">

    $(document).ready(function () {
       $('th[scope^=col]') ???
    })

</script>

The problem is though, that I don't know what should replace ???. Does anyone have any idea? I'm thinking I need some JavaScript or JQuery code that grabs the anchor and then appends the extra query string parameter. Question is what exactly should the code be?

Thanks,

Sachin

Upvotes: 1

Views: 244

Answers (3)

Sagar Patil
Sagar Patil

Reputation: 1948

Try this:

$(document).ready(function(){

   $('th[scope^=col]').each(function(){

      var old_link = "";
      var new_link = "";
      //Get the current href value of the child anchor tag of 'th[scope^=col]'
      old_link = $(this).children('a').attr('href');
      //Append the extra string required '(in this case &page=3)' to the old_link
      new_link = old_link + '&page=3';
      //Set the href value for the anchor tag within 'th[scope^=col]'
      $(this).children('a').attr('href',new_link);

   });

});

Hope this helps.

Upvotes: 3

ShankarSangoli
ShankarSangoli

Reputation: 69905

Try this

$(document).ready(function () {
   $('th[scope=col] a')[0].href += "&page=3";
});

If you think the url can already contain page param in the querystring and you just have to update its value then use this code.

$(document).ready(function () {
   $a[0].href = $a[0].href.replace(/([?&])page=[^&]*&?/,'$1') + '&page=3';
});

Upvotes: 3

xdazz
xdazz

Reputation: 160833

$(document).ready(function () {
   $('th[scope=col] a').each(function(){
        $this = $(this);
        $this.attr('href', $this.attr('href') + '&page=3');
   });
});

Upvotes: 1

Related Questions