How To Stop An Object From Generating Additonal Copies Of The Same Content?
Every time when I press the button it keeps outputting the same data additionally. I don't want that because I don't want my users on my website to accidentally press the button ag
Solution 1:
You continously append to output.
Just change
var output;
varXHR = function() {
output = "";
...
Like this
$(function() {
var z = $('.z'); // Grab class z to togglevar x = $('#x');
var output;
varXHR = function() {
output = "";
var data = {
"shop": [{
"item": "Ps3",
"cost": "$150"
},
{
"item": "xbox 360",
"cost": "$140"
},
{
"event": "Black Friday",
"date": "4-25-2018"
},
{
"special_guest": "John Doe",
"time": "4:30 pm"
}
]
}
$.each(data.shop, function(index, element) {
for (var j in element) {
output += element[j] + '<br>';
}
});
x.html(output);
};
$("button").click(function() {
XHR();
});
});
h1 {
color: gold;
}
#x {
color: white;
text-align: center;
}
.z {
background-color: red;
width: 250px;
margin: auto;
padding-bottom: 5px;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><divclass="z"><h1>Details </h1><h2id="x"></h2></div><button>Click</button>
Solution 2:
You can use the .one()
method to run the click handler only the first time.
$("button").one("click", XHR);
Solution 3:
You have different options, some of them...
- Disable the button once is pressed.
- Remove the button once is pressed.
- The "one()" solution proposed by barman (very clean).
- Checking the content of "#x" before adding the content, just doing it if is empty.
All will work, and I would choose one depending on your interface and what it feels better for the user. Maybe make the button disappear is strange for your case, etc.
Also. if you want the function (XHR) to remain active, so maybe you want to reactivate it in some situation, then maybe 1, 2 or 4 are the way to go.
You can do all that inside the onclick event function or inside your XHR function. For example, for the 4 option...
$('button').click(function(){
if ($('#x').html() != '')
XHR();
});
I hope it helps!
Post a Comment for "How To Stop An Object From Generating Additonal Copies Of The Same Content?"