1

Suppose you have a link that contains some values:

<a href="/action?number_one=1&number_two=4" class="some_link"> something </a>

How can you increment number_one and number_two when a user clicks on this link using jQuery?

I know to extract number_one's value you can use regex:

var number_one = $(this).attr("href").match(/number_one=([0-9]+)/)[1];

How can you then increment it say by 20, so that it now becomes:

<a href="/action?&number_one=21&number_two=24" class="some_link"> something </a>
Community
  • 1
  • 1
john mossel
  • 2,158
  • 5
  • 24
  • 39

2 Answers2

1

This works in Chrome, at least - the .search attribute is an HTML5 property:

// get the real link element
var link = $(this).get(0);
var fields = {};

// parse and increment number one
fields.number_one = link.search.match(/number_one=([0-9]+)/)[1];
fields.number_one += 20;

// do same for number two:
fields.number_two = link.search.match(/number_two=([0-9]+)/)[1];
fields.number_two += 20;

// update the link's query parameters
link.search = $.param(fields);
Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • For me it concatenates the Strings - also could you possibly tell what the `search` attribute on a link is? I got it working this way: http://jsfiddle.net/TNAba/. – pimvdb Apr 02 '11 at 21:32
  • pimvdb, you way works however it returns the link as /number_one=21 istead of the full link: action?number_once=21 – john mossel Apr 02 '11 at 21:48
  • `$(this).get(0)` is the same as just `this` – Šime Vidas Apr 02 '11 at 22:59
0

This should do it for any number of url-query var=number pairs:

var fixed_url = $(this).attr("href").replace(
        // This regex matches a url-query var=number
        /([?&]\w+=)(\d+)(?=[&#]|$)/g,
        // This function increments the value by one.
        function(m0, m1, m2) {
            return m1 + (Number(m2) + 1);
        });

Edit: Removed invalid jQuery assignment.

ridgerunner
  • 33,777
  • 5
  • 57
  • 69
  • WOuld it work if you also had a non-number var, e.g. ?var1=text&var2=4 – john mossel Apr 02 '11 at 21:56
  • It simply skips over any url-query `var=value` pair where the value has any non-digits (and leaves them unchanged). It modifies only those where the value is purely digits. – ridgerunner Apr 02 '11 at 22:34
  • That code is invalid. You cannot set the value of `$(this).attr("href")` by assigning something to it. – Šime Vidas Apr 02 '11 at 23:00
  • @Šime Vidas: Thanks for pointing that out. Although I tested the `.replace` operation, I am not familiar with jQuery. Fixed. – ridgerunner Apr 03 '11 at 00:35