inperspective
inperspective

Reputation: 1904

Click Once For All Elements In Same Class

I am trying to write code that will add another row to a form automatically. It should only do this once for each form input with the class lastName.

The below code works. But it executes more than once. I want the code to only execute once for each form input with the class lastName. I am inexperienced with jquery and javascript, so I am unsure of how to approach this problem.

    function AutoAdd() {
    $('.lastName').focus(function(e){
    $('#add_new',pupils_form).parent().before(pupils_row);

    AutoAdd();
    });
    };
    AutoAdd();

Upvotes: 1

Views: 186

Answers (3)

Ram
Ram

Reputation: 144659

You can use the one method:

Attach a handler to an event for the elements. The handler is executed at most once per element.

$('.lastName').one('click', function(e){
      $('#add_new',pupils_form).parent().before(pupils_row);
});

Also as you are binding a handler for the inputs you can put the handler outside of the function, note that your function calls itself and runs continuously. If you want to execute the handler on page load you can trigger the event:

$('.lastName').focus(function(e){
      $('#add_new',pupils_form).parent().before(pupils_row);
}).focus()

For dynamically generated elements, you should delegate the event, try the following:

$(document).on('focus', '.lastName', function(){
     $('#add_new',pupils_form).parent().before(pupils_row);
})

You can use data-* attributes, try the following:

<input type='text' class='lastName' data-run='go'/>

$(document).on('focus', '.lastName', function(){
     if ( $(this).data('run') == 'go') {
           $('#add_new',pupils_form).parent().before(pupils_row);
           $(this).data('run', 'stop')
     }
})

Upvotes: 1

powerbuoy
powerbuoy

Reputation: 12838

To avoid having to run your AutoAdd function on newly created rows, you can use jQuery's on()-function instead of focus():

$('#the-form').on('focus', '.lastName', function () {
    $('#add_new',pupils_form).parent().before(pupils_row);
});

on() actually attaches to the form (you'll wanna change the selector #the-form) and listens to events that bubble up from children of said form.

Upvotes: 0

fengd
fengd

Reputation: 7569

you are having an infinite call stack here. your AutoAdd will call itself again and again and ...

Upvotes: 0

Related Questions