Reputation: 4677
I have a link whose text content is determined by some backend software. Depending on what the text content is, that link should be clickable or not clickable. I am trying to make the link not clickable if the link text is "No New Messages". I am trying to use the following code:
if ($('a#full_notifications_link').text() == "No New Messages"){
$('a#full_notifications_link').click(function(){
return false;
});
}
This is not working. The link works just like normal. How do I get the link to not work if the link text is "No New Messages"?
To be clear, I CANNOT change any of the html because it will be different every time depending on the backend. Also, I've determined the problem is with line 1, because if i place an alert right after it the alert does not appear.
Also, here is the html when the text says "No New Messages":
<a data-remote="true" href="/usernotificationslist" id="full_notifications_link">
No New Messages
</a>
Upvotes: 0
Views: 90
Reputation: 388
You can use preventDefault to do this, by catching the click event
BTW this is not working to me i don't know why the onclick does not find the function to be binded hehe
Even though this the best approach I think http://jsfiddle.net/A2wns/1/
// HTML
<a href="..." onclick="checkMessage()">No New Messages</a>
// js
function checkMessage(evt){
if ( $(evt.target).text() === "No New Messages"){
evt.preventDefault();
}
}
Upvotes: 0
Reputation: 2403
Please see this Fiddle: http://jsfiddle.net/jFIT/J8eEL/
$('a#full_notifications_link').click(function(event){
if ($.trim($('a#full_notifications_link').text()) == "No New Messages"){
event.preventDefault();
return false;
}
});
returning return false from a function doesnt usually do it.. event.preventDefault();
Upvotes: 1
Reputation: 237
Make sure you have no spaces to meet the condition right.. To be sure, dont line break them
<a data-remote="true" href="/usernotificationslist" id="full_notifications_link">No New Messages</a>
also, have you already placed these inside?
$(document).ready(function(){
//enter code here
});
Upvotes: 0
Reputation: 1991
HTML
<a href="javascript:myfunction();" id="full_notifications_link">text</a>
JAVASCRIPT
function myfunction(){
var text_of_link = $('a #full_notifications_link').text();
if(text_of_link == "No New Messages"){
//do nothing
}else{
window.location.replace($('#full_notifications_link').attr("href"));
}
}
Upvotes: 1