Problem with breaking out Jquery each loop?-Collection of common programming errors
What you are doing:
for every existing row R
if R.id == newRow.id
alert
break
else
add newRow
This will add the newRow for each row that comes before an existing row with that id. With rows [1,2,3,4,5,6,7,8,9] and adding a row 9 will add that row 8 times before alerting “already exists”.
What you mean to do is:
exists = false
for every existing row R
if R.id == newRow.id
existing = true
alert
break
if !exists
add newRow
Equivalent in JS:
addToTable = function() {
var selected = $("select[name*='mySelect'] option:selected").val();
var exists = false;
$('#myTable').find('tr').each(function() {
if ($(this).attr('id')==selected) {
alert('Record has already existed!');
exists = true;
return false;
}
});
if(!exists) {
$('#favourite_hotels_table').append('
'+selected+'
‘); } }