Claudio
Claudio

Reputation: 3824

Jquery: function keeps executing on element after its class has been removed

I am trying to add rows to a table after blurring the very last input. It is working pretty well, but it is adding a new row every single time I blur any input. Here is the code:

<script type="text/javascript">
var i = 1;
$(function() {
$('#addNew').click(function() {

$('input').removeClass('last');

$('#all_items tr:last').after('<tr><td><input type="text" name="item_'+i+'" id="items_'+i+'" class="last field" /></td><td>and other input fields</td></tr>');

$.ajax({
    url: "js/autocomplete.php?count="+i,
    success: function(newhtml){
        newhtml += "<";
        newhtml += "/script>";
        $("head").append(newhtml);
    }
});

i++;
});

//on blur click on addNew
$('.last').blur(function() {
$('#addNew').trigger('click');
});

});
</script>

autocomplete.php is like:

<script>
  $(function() {
    //this section autocompletes the rows. Disregard for this question
    var data = [-data retrieved by a function, working well!-];
     $( "#items_'.$count.'" ).catcomplete({ delay: 0, source: data,
        select: function(event, ui) {
            $("#price_'.$count.'").val(ui.item.price);
            $("#category_'.$count.'").val(ui.item.category);
        }
         });
  });

$(".last").blur(function() { 
  $("#addNew").trigger("click");
});
</script>

and the html:

<span id="addNew">Add Item</span>

<table id="all_items">
<tr id="header"><th>Item</th><th>Note</th><th>Quantity</th><th>Price</th></tr>
<tr id="first"><td><input type="text" name="item_0" id="items_0" class="last text" /></td>
    <td><input type="text" name="item_note_0" id="item_note_0" /></td>
    <td><input type="number" name="quantity_0" id="quantity_0" value="1" /></td>
    <td><input type="text" name="price_0" id="price_0" />
        <input type="hidden" name="category_0" id="category_0" /></td></tr>
</table>

By inspecting elements (Chrome) I can see the class 'last' is removed, but those fields still add a row/input at the end of the table when I blur them. What am I doing wrong? How can I avoid them keeping that behavior?

Upvotes: 2

Views: 493

Answers (1)

Adil
Adil

Reputation: 148150

The event is attached with elements having class last are never removed when you remove class from the element. You have to unbind the event along with removing class from the element. You can use unbind() to remove the event from elements.

$('.last').unbind();

Upvotes: 4

Related Questions