I have some html element like these:
<table id="myTable"></table>
<select name="mySelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<a href="javascript:void(0)" onclick="addToTable()">Add new</a>
<script>
addToTable = function() {
var selected = $("select[name*='mySelect'] option:selected").val();
$('#myTable').find('tr').each(function() {
if ($(this).attr('id')==selected) {
alert('Record has already existed!'); return false;
}
else $('#myTable').append('<tr id="'+selected+'"><td>'+selected+'</td></tr>');
});
}
</script>
The problem was: when I added two records (rows) with the same id, it alerted the message but kept appending the new row instead of breaking out the loop. What was I wrong here?
Thanks in advance.
What you are doing:
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:
Equivalent in JS: