Reputation: 3512
The code below runs through a list of items that have the class .removeFood. If the clicked food name matches the items on the list it is replaced with blank text.
Example list:
Nachos
Fries
Nachos
Burger
Nachos
The problem: If there are duplicates on the list it removes all of the matches. So in the list above it would remove all 3 "nachos" - How do I only remove the first match?
$(".removeFood").click(function() {
$(this).text('')
if (food1.trim() == removeThis.trim()){
$("#newFoodName1" ).text('')
}
if (food2.trim() == removeThis.trim()){
$("#newFoodName2" ).text('')
}
if (food3.trim() == removeThis.trim()){
$("#newFoodName3" ).text('')
}
if (food4.trim() == removeThis.trim()){
$("#newFoodName4" ).text('')
}
if (food5.trim() == removeThis.trim()){
$("#newFoodName5" ).text('')
}
})
Upvotes: 0
Views: 60
Reputation: 22490
More number of same variable validation better with use switch
instead of if
$(".removeFood").click(function() {
$(this).text('')
switch (removeThis.trim()) {
case food1.trim():
$("#newFoodName1").text('')
break;
// like wise
}
})
Upvotes: 1
Reputation: 939
Use "else if" for the consecutive ifs in the code. If all conditions will be "if" it will execute all of them.
Upvotes: 2