Reputation: 259
I want to append text boxes when user clicks on button to body.But i want to append them only once while user is on that page.I have tried using counter to do that.But there is some minor issue.
<script type="text/javascript">$(document).ready(function(){
var k=0;
$('#show').click(function(){
if(k==null){
for(i = 0; i < 5; i++) {
$('body').append('<br/>guve your name<input type="text" id="div'+ i +'" />');
};
};
k=1;
});
});</script>
in html
<button id="show">Hii</button>
Upvotes: 2
Views: 493
Reputation: 28611
You have multiple choices here:
Check if the element exists (simplest).
As you're adding divs with IDs, they can be checked directly, which saves you needing to worry about a variable.
$('#show').click(function() {
if ($("#div0").length == 0) {
for(i = 0; i < 5; i++) {
$('body').append('<br/>give your name<input type="text" id="div'+ i +'" />');
};
}
});
Use one()
(least favourable option imo)
$('#show').one(function() {
for(i = 0; i < 5; i++) {
Remove (or disable) the button once it's been clicked
(the only sensible option for UX, that can be combined with one() if desired)
$('#show').click(function() {
$('#show').hide();
for(i = 0; i < 5; i++) { ...
Upvotes: 0
Reputation: 115222
Use one()
method to attach event handler, which only executes handler once for event type and element.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#show').one('click', function() {
for (i = 0; i < 5; i++) {
$('body').append('<br/>guve your name<input type="text" id="div' + i + '" />');
};
});
});
</script>
<button id="show">Hii</button>
Upvotes: 3