I want to add Jack
in the end of a string only one time. How?
$('button').click(function() {
$('div').append('Jack');
});
<script src=".8.3/jquery.min.js"></script>
<div>My name is: </div>
<button>click</button>
I want to add Jack
in the end of a string only one time. How?
$('button').click(function() {
$('div').append('Jack');
});
<script src="https://ajax.googleapis./ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>My name is: </div>
<button>click</button>
In other word, when I click on that button, if Jack is appended, then nothing happens, but if Jack is not exist, then it appends.
Share Improve this question asked Dec 10, 2015 at 22:51 stackstack 10.2k22 gold badges70 silver badges130 bronze badges3 Answers
Reset to default 2$('button').click(function() {
$('div').html('Jack');
});
This will replace whatever is inside the div
$('button').click(function() {
var text = $('div').text();
if(!/Jack/.test(text)){
$('div').append('Jack');
}
});
<script src="https://ajax.googleapis./ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>My name is: </div>
<button>click</button>
Use jQuery's on()
and off()
methods to easily control when event listeners are active.
To add an onclick listener:
$("button").on("click", function(){});
To remove the listener:
$("button").off("click");
In your case, you can put the off()
function call inside of the on()
function's callback. The result is an anonymous function that will run once, on a single click, and then remove itself.
$("button").on("click", function(){
$("div").append("Jack");
$(this).off("click");
}
Or even better, use one()
, which will fire only once per element.
$("button").one("click", function(){
$("div").append("Jack");
}