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:
<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:
$("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:
$('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
You use 'on' as $(document) instead of $('input:text') and then you use 'input:text' as the second argument to on() when you use the object syntax like that. It's cool, actually. Nice job jQuery:
http://jsfiddle.net/DBGWs/
http://api.jquery.com/on/
You don't -have- to bind to document, you can also do any element which contains the new elements. In this fiddle I didn't have any, so I used document instead.
Hi,
Thank you very much, it worked like a charm!
Thread Information
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
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
Forum Rules
Bookmarks