Question

I have several a tags on a dynamically generated web page and they are like this

<a href='JavaScript:SWESubmitForm(document.SWEForm9_0,s_12,"s_9_1_35_1","1-3ZR4-1743")'  tabindex=997  id='s_9_1_35_1'>Add</a>

<a href='JavaScript:SWESubmitForm(document.SWEForm9_0,s_13,"s_9_1_36_1","1-3ZR4-1743")'  tabindex=997  id='s_9_1_36_1'>Cancel</a>

several others like mentioned above. I need to execute some logic when link with text 'Add' is clicked. I know one of the way is to attach click event to a tags and then check for text.

$('a[href*="SWESubmitForm"]').click(function(){
if($(this).text() == "Add"){
//do something
}

but I am not sure if this is most efficient way to do this.

Can you guys please suggest the right way of doing this?

Was it helpful?

Solution

Your code works but you have problems with brackets.I tested on jsfiddle

$('a[href*="SWESubmitForm"]').click(function(){
if($(this).text() == "Add"){
//do something
    alert('ok')}
});​

OTHER TIPS

You could use filter for this.

As you posted in another answer that you wanted to know whether this is 'the right way' - I would say no. The right way would of course be to assign a class to each of these links then use a class selector to bind the click event to them. But I am assuming that you don't have too much control over the html.

That being said I would use filter as I have suggested below. This minimizes the number of events which are bound. If you want to make it even more efficient I would instead make use of delegate or on and bind to a common parent. This reduces the number of bound click events also.

http://jsfiddle.net/mrtsherman/Uypuq/

$('a[href*="SWESubmitForm"]').filter(function() {
    if ($(this).text() == "Add") {
        return true;
    }
}).click(function() {
    alert();
    return false;
});​

If the link id is predictable and as shown in your HTML, you can just use this:

$('#s_9_1_35_1').click(function() {
    // put your code here
});

If you control the HTML, you can either put an appropriate ID or class on the desired links and just use selectors off those. That is much more efficient than trying to filter all links based on their text.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top