Button text toggle in jquery
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>
http://jsfiddle.net/DQK4v/
Thanks.
You can use text
method:
$(function(){
$(".pushme").click(function () {
$(this).text(function(i, text){
return text === "PUSH ME" ? "DON'T PUSH ME" : "PUSH ME";
})
});
})
http://jsfiddle.net/CBajb/
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.