Reputation: 241
I am trying to change/revert a text string when a link is clicked with Jquery. Now the first statement of this code works fine, but the the other one doesn't. Can someone please help figure out what's going wrong here?
<script>
$("document").ready(function(e) {
$("#newMessagelink").click(function(e) {
$("#new-msg").toggle();
if($("#newMessagelink").text("New Message") {
$("#newMessagelink").text("Back to Inbox");
} else if($("#newMessagelink").text("Back to Inbox")) {
$("#newMessagelink").text("New Message");
}
})
});
</script>
thanks!
Upvotes: 0
Views: 50
Reputation: 67217
Try to use .text()
properly,
$("document").ready(function(e) {
$("#newMessagelink").click(function(e) {
$("#new-msg").toggle();
var txt = $(this).text();
$(this).text(txt == "New Message" ? "Back to Inbox" : "New Message");
});
});
.text("something")
will return a jquery wrapper object
. If you pass it in a if statement
, then it always evaluates to true
. So fetch the text of the target element and check it properly.
Also you had some syntax errors like, not closing the opened parenthesis etc. Its better to see your console once before bringing your issues to other's attention.
Upvotes: 2
Reputation: 115282
Your if
statement will be always true since text(string)
returns jQuery object always. Instead you can do something simple using text() with callback
. Also you can use this
instead of #newMessagelink
selector, since inside the click handler this
refers to #newMessagelink
.
$("document").ready(function(e) {
$("#newMessagelink").click(function(e) {
$("#new-msg").toggle();
$(this).text(function(i, text) {
return text == "Back to Inbox" ? "New Message" : "Back to Inbox";
});
})
});
with your own code change the if condition properly
$("document").ready(function(e) {
$("#newMessagelink").click(function(e) {
$("#new-msg").toggle();
var text= $(this).text();
if(text=="New Message") {
$(this).text("Back to Inbox");
} else if(text=="Back to Inbox") {
$(this).text("New Message");
}
})
});
Upvotes: 1