Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Feb 2009
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts

    how to bind focus and blur on new elements

    Hi, I am having trouble binding focus and blur to new elements.

    I have the following HTML code:
    Code:
        <div class="ticket">
            <input class="firstname" name="firstname[]" title="First Name(s)" value="" />
            <input class="lastname" name="lastname[]" title="Last Name" value="" />
            <a href="#"><img src="/images/admin/DeleteRed.png" /></a> OR
            <a href="#" class="add">Add more</a>
        </div>
    I then have the following jquery code attached to 'Add more' hyperlink:

    Code:
        $("body").on("click", "a.add", function() {
            var content = $(this).parent('.ticket').html();
            var newdiv = $("<div class='ticket'>");
            newdiv.html(content);
            $(this).parent('.ticket').after(newdiv);
            return false;
        });
    As you can see, all it does is copy the current div and add it straight after.

    The input fields within the div tag have the following jquery bound to it:

    Code:
    $('input:text').on({
        focus: function () {
            var self = $(this);
           
            if (self.val() == self.attr('title')) {
                self.val('');
            };
        },
        blur: function () {
            var self = $(this),
                val = jQuery.trim(self.val());
           
            if (val == "" || val == self.attr('title')) {
              self.val(self.attr('title')); 
            };
        }
    }).trigger('blur');
    It does seem to copy the div tag and place it right after the current one, however, it does not bind focus or blur to the newly added elements.

    What am I doing wrong?

    thanks

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    You are using .on(), which is generally correct. But also .on() (as all the other jQuery methods) can only be bound to elements that already exist at that point of time.

    Now, .on() supports event delegation ... which means: You bind the event handler using .on() not directly to the element, but to one of its parent elements that already exists in the DOM. You did exactly that for "a.add", just copy this behavior to "input:text"
    Code:
    $(document).on("focus", "input:text", function() {
       ...
    }).on("blur", "input:text", function() {
       ...
    });


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •