Reputation: 407
good day!
I have a problem, this is when I click on my button for ajax request this works perfectly and display the data on my select item but, when I click again on the button for ajax request, this give the data (this is correct) but on my select item this show again the data so, I have the same data two times, how can I solve this? I´m new into JS and this is for my school project haha, so Thank u so much if u can help me! <3
this is my js code
$("#hola").click( function(e) {
e.preventDefault();
$.ajax({
method: 'GET',
url: '/api/check-estudio/',
data: {},
dataType: 'json',
cache: true,
success: function(data) {
for (var i=0; i<data.length; i++) {
console.log(data[i]);
var optionHTML = '<option>' + data[i].name + '</option>';
$(".selectEstudio").append(optionHTML);
}
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
});
When I click first time work perfectly and display my data on my select box and show the options.
When I close de modal and Click again the button for show modal and ajax request, display two times the same info.
THANK U FOR YOUR TIME! <3
Upvotes: 2
Views: 1866
Reputation: 1774
It's because of you are appending same data into select
over and over again. Instead of doing that, you can generate the option
tags first then append it to select
's innerhtml once for every request like that :
var optionsArray = [];
for (var i = 0; i < data.length; i++) {
var optionElement = $('<option>', '</option>');
optionElement.text(data[i]);
optionsArray.push(optionElement);
}
$(".selectEstudio").append(optionsArray);
For readability i can say that avoid hard-coding html tags with in strings. Just create them with jQuery's selector like this : $('<option>', '</option>')
. This approach gives you chance of extending element's attributes with more elegant and readable way, and there is no need for for
loop here since you are just creating bunch of element every time. Just use map
function and assign elements to array explicitly like this :
var optionsArray = data.map(function(current) {
var optionElement = $('<option>', '</option>');
optionElement.text(current);
return optionElement;
});
$(".selectEstudio").append(optionsArray);
It's much readable right ?
Upvotes: 2
Reputation: 72289
Instead of .append()
use .html()
along with a bit code enhancement:-
var optionHTML =''; // define variable
for (var i=0; i<data.length; i++) {
optionHTML += '<option>' + data[i].name + '</option>'; // add all options
}
$(".selectEstudio").html(optionHTML); // append in last not inside loop one-by-one
Or you can first empty() select-box and then add again:-
var optionHTML ='';
$(".selectEstudio").empty();
for (var i=0; i<data.length; i++) {
optionHTML += '<option>' + data[i].name + '</option>';
}
$(".selectEstudio").html(optionHTML);
Upvotes: 2