1

I have a page with several (100+) entries like this:

<a href="javascript:removeFromCart(12302, 2);" class="remove">Remove</a>

Now I am looking for a jQuery snippet which can be run in the console and helps me to "click" all those "links" and execute the javascript function removeCart() with the respective parameters.

This does not work:

$("a[href^='javascript']:contains('Remove')").click()

Any ideas?

2

6 Answers 6

7

You can’t use .click() here, because there is no event binding for the anchor. You need to manually execute the contents of the href attribute, and that can easilly be done using eval():

$('.remove').each(function() {
    eval(this.href);
});
Sign up to request clarification or add additional context in comments.

7 Comments

There's no need to use eval here.
@AndrewWhitaker what's your proposed solution?
@AndrewWhitaker "need" - is that a joke? It’s a solution and it works. You shouldn’t downvote based on your personal vendettas against perfectly useable javascript core functions.
@David: Set window.location.href like the duplicate mentions: jsfiddle.net/Q9ZTc/2
imo setting window.location to run JS is way more dirty than eval. +1 for a solution that works.
|
2

You can add a new field and pass the parameters there like <a href="#" data-a="12302" data-b="2" class="remove">Remove</a>

$("a.remove").each(function(){
    var param1 = $(this).data('a');
    var param2 = $(this).data('b');
    removeFromCart(param1, param2);
});

Comments

1

.trigger("click") does not actually perform a user click, but any code binding to the "click" event. You need to set the window location instead:

$("a[href^='javascript']:contains('Remove')").each(function() {
  window.location.href = $(this).prop("href");
});

1 Comment

Since we've included a check for the javascript protocol inside the href in our selector we don't need to worry.
0
 $('.remove').trigger('click',function(){
       // place your code
 });

Comments

0

You can move the parameters in the javascript function to data attributes first

<a href="#" data-param1="20433" data-param1="2" class="remove">Remove</a>

then work on the class selector.

$("a.remove").each(function() {
  var param1 = $(this).attr('data-param1');
  var param2 = $(this).attr('data-param2');
  removeFromCart(param1, param2);
});

Comments

0

Well, the only way to trigger the code is actually to execute it.

$("a[href^='javascript:removeFromCart']").each(function() {
    eval($(this).attr('href').substr(11));
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.