When i click ".pushme" button, it turns its text to "Don't push me". I want to turn the text again to "push me" when button is clicked again. How can i do that?
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button class='pushme'>PUSH ME</button>
<script>
$(".pushme").click(function () {
$(this).text("DON'T PUSH ME");
});
</script>
</body>
</html>
Thanks.
You can also use math function to do this
var i = 0;
$('#button').on('click', function() {
if (i++ % 2 == 0) {
$(this).val("Push me!");
} else {
$(this).val("Don't push me!");
}
});
With so many great answers, I thought I would toss one more into the mix. This one, unlike the others, would permit you to cycle through any number of messages with ease:
var index = 0,
messg = [
"PUSH ME",
"DON'T PUSH ME",
"I'M SO CONFUSED!"
];
$(".pushme").on("click", function() {
$(this).text(function(index, text){
index = $.inArray(text, messg);
return messg[++index % messg.length];
});
}??????????????????????????????????????????????);?
Use an if/else statement.. or ternary if you understand it
$(".pushme").click(function () {
var $el = $(this);
$el.text($el.text() == "DON'T PUSH ME" ? "PUSH ME": "DON'T PUSH ME");
});
If you're setting the button text by using the 'value' attribute you'll need to set
instead of:
Also in my situation it worked better to add the JQuery direct to the onclick event of the button:
onclick="$(this).val(function (i, text) { return text == 'PUSH ME' ? 'DON'T PUSH ME' : 'PUSH ME'; });"
$(".pushme").click(function () {
var button = $(this);
button.text(button.text() == "PUSH ME" ? "DON'T PUSH ME" : "PUSH ME")
});
This ternary operator has an implicit return.
If the expression before ?
is true
it returns "DON'T PUSH ME"
, else returns "PUSH ME"
This if-else statement:
if (condition) { return A }
else { return B }
has the equivalent ternary expression:
condition ? A : B
I preffer the following way, it can be used by any button.
<button class='pushme' data-default-text="PUSH ME" data-new-text="DON'T PUSH ME">PUSH ME</button>
$(".pushme").click(function () {
var $element = $(this);
$element.text(function(i, text) {
return text == $element.data('default-text') ? $element.data('new-text')
: $element.data('default-text');
});
});
You could also use .toggle()
like so:
$(".pushme").toggle(function() {
$(this).text("DON'T PUSH ME");
}, function() {
$(this).text("PUSH ME");
});
More info at http://api.jquery.com/toggle-event/.
This way also makes it pretty easy to change the text or add more than just 2 differing states.
Use a custom ID if possible if you would like to apply the action to only that button.
<button class="pushDontpush">PUSH ME</button>
$("#pushDontpush").click(function() {
if ($(this).text() == "PUSH ME") {
$(this).text("DON'T PUSH ME");
} else {
$(this).text("PUSH ME");
};
});
Working CodePen: Toggle text in button
Source: Stackoverflow.com