Shad Gagnon
Shad Gagnon

Reputation: 513

Changing onclick attribute using replace with jQuery

Do someone know what is the best way to replace some string inside a onclick attribute ?
I need to get the current value and replace some text inside parameters.

Exemple,
I have this link:

<a href="#" onclick="myfunction('parameter1a','parameter1b')">My link</a>

And I want this:

<a href="#" onclick="myfunction('parameter2a','parameter2b')">My link</a>

In other words, I want something like this:

$('a').attr('onclick', $(this).attr('onclick').replace('1', '2'));

And I know I can do this, but I need something dynamic retreiving the values of current element:

$("a").attr('onClick', "myfunction('parameter2a','parameter2b')");

Finally it working when I made a simple demo: http://jsfiddle.net/GkWhh/4/

Thank you for your solutions !

Upvotes: 3

Views: 35219

Answers (3)

Ram
Ram

Reputation: 144729

$('a[onclick]').attr('onclick', function(i, v){
   return v.replace(/1/g, '2');
});

http://jsfiddle.net/cj9j7/

If you need something more dynamic do not use onclick attributes, changing onclick attributes is hackish, you can use click method instead.

var param = 1;
$('a').click(function(){
   // ...

   if ('wildguess') {
     param = 1;
   } else {
     param++;
   }
})

Upvotes: 11

Jai
Jai

Reputation: 74738

You can do this: http://jsfiddle.net/SJP7k/

var atr = $('a').attr('onclick');
var str = atr.split('1');
var natr = str.join('2');
$('a').attr('onclick',natr);

Upvotes: 0

roman
roman

Reputation: 11278

sounds like a really bad idea but anyway - you can access the string value of the onlick attribute using something like that:

$('a').each(function() { this.attributes.onclick.nodeValue = this.attributes.onclick.nodeValue.replace('1', '2'); })

Upvotes: 1

Related Questions