Reputation: 43
I have a form that when a user submits values, the jquery script I have calculates the form values and outputs the calculated data.
This works fine except if a user clicks on the submit button again it appends my lopped data to the existing data (which is duplicated or new data is re-appended).
If the user clicks submit twice I just want it to overwrite the existing looped output.
for (i = 1; i <= $jumps; i++) {
if (i == 1) {
var $num = $jumpSize * i;
} else if (i == 2) {
var $num = ($jumpSize * i) + $stops;
} else {
var $num = ($jumpSize * i) + ((i - 1) * $stops);
}
$('.output').append("<p>Num:" + i + " " + parseInt($num) + "</p>");
}
Is it possible to replace the looped data if the users hits the submit button twice.
Here's a demo http://jsfiddle.net/knard/EY8MJ/13/
Upvotes: 1
Views: 187
Reputation: 545
I experienced he same problem. here is how I solved it. Lets Say you are expecting a new response everytime a request is made with ajax
$.ajax({
url: "scanner/",
type: "POST",
data: {
'csrfmiddlewaretoken': csrf,
'barnumber': $("#search-input").val(),
'id':id
},
success: function (res) {
const data = res.data
console.log(data)
$('student-result').html("");
data.forEach(e=>$('#student-result').html(`
<tbody >
<tr>
<td>Name:</td>
<td class="font-medium text-dark-medium">
${e.lname}
${e.fname}
</td>
</tr>
</tbody>
`));
});
Points to note. Instead of using .append method to render the data use .html which renders directly to the element id replacing it
Upvotes: 1
Reputation: 8181
Try:
$('.output').empty().append("<p>Num:" + i + " " + parseInt($num) + "</p>");
Upvotes: 0
Reputation: 2683
Before loop add this line $('.output').html("");
So it will clear contents, when submit button is pressed. Demo: http://jsfiddle.net/EY8MJ/14/
Upvotes: 0
Reputation: 8406
Use .html instead of .append to replace the content. For example...
$('.output').html("<p>Num:" + i + " " + parseInt($num) + "</p>");
Upvotes: 2