Joe Half Face
Joe Half Face

Reputation: 2333

Modify link before sending request (with Jquery)

My issue is that I have some links on the page, which at the moment are ruby-generated in html file. So, when user loads page, links are created and based on some database data. But, there is also one option, that is not DB-generated, and should work in the real time.

For example, if button 'A' is submited currently, links should request:

http://url/?(ruby generated parametrs)&button=A.

Then user clicks button 'B', and links request:

http://url/?(ruby generated parametrs)&button=B

To sum it up, basically, Jquery should add one additional parametr to link, and then send request to server.

Is this possible? How can I do that?

P.S. I strongly dislike idea of reloading all links on the page on submitting one of options button, it is connected with specific app functions, there are A LOT of such links on the page.

Code:

 array[i]="<span id='width_measure_#{i}'>"+(link_to(array[i], {:controller =>'tests',  :action => 'add_key', :keyword => array[i], :position=>i}, :class=>'unsaved_links', :id=>i, :method => :post, :remote => true))

HTML output:

<a href="/tests/46/add_key?keyword=TEST&amp;position=0" class="unsaved_links" data-method="post" data-remote="true" id="0" rel="nofollow">TEST</a>

Wanted eventual request:

<a href="/tests/46/add_key?keyword=TEST&amp;position=0&amp;button=A" class="unsaved_links" data-method="post" data-remote="true" id="0" rel="nofollow">TEST</a>

Upvotes: 1

Views: 152

Answers (2)

Zain Shaikh
Zain Shaikh

Reputation: 6043

try following. DEMO here

HTML

<a id="buttonA" href="http://yahoo.com" target="_blank">Yahoo</a>
<a id="buttonB" href="http://google.com" target="_blank">Google</a>
<a id="buttonC" href="http://twitter.com" target="_blank">twitter</a>

jQuery

$('a').each(function(){

    var newUrl = $(this).attr('href') + '?button=' + this.id;
    $(this).attr('href', newUrl);

});

Upvotes: 0

yckart
yckart

Reputation: 33378

I think what you want is a simple replacement, or rather an string-appending:

$("a").click(function() {
    this.href += "&button=" + this.id;
});

http://fiddle.jshell.net/N2Yvv/

Upvotes: 4

Related Questions