Smile
Smile

Reputation: 2758

Bind jQuery events to DIV with specific HTML TAG like TEXTAREA

I have one DIV element which contains dynamically created TEXTAREAs and <input type="file"/> and <input type="checkbox"/>.

Currently I have bound three events on above DIV like below

jQuery("#uniqueId ").bind("click change keypress", function(e){
    ....
    ....
});

Now problems occur are when I click on file input button to Browse and Upload a file or check on Checkbox I receives following error

Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable. 

myxFunction myXjavscript.js:1172
(anonymous function) myXjavscript.js:109
f.event.dispatch jquery-1.7.1.min.js:3
h.handle.i

and because of it file and checkbox inputs are not working and throwing errors. I just want to bind above events only on TEXTAREA and not other elements under a DIV.

Reason to use "click change keypress" events together because in Chrome I am performing Dynamic operations on Textarea to get cursor position after add/edit/delete texts from Textarea. So to record all those things I needed to add those three events.

How can I achieve this?

Upvotes: 0

Views: 945

Answers (2)

Sean Johnson
Sean Johnson

Reputation: 5607

If you only want to bind the events to the textareas contained within #uniqueId, use the second argument (delegate selector):

jQuery("#uniqueId ").on("click change keypress", "textarea", function(e){
    ....
    ....
});

Edit: didn't realize you were using .bind, always use .on! It's awesome. http://api.jquery.com/on/

Upvotes: 1

Rohan Kumar
Rohan Kumar

Reputation: 40639

You should check the element before using it like,

if(jQuery("textarea#uniqueId").length)
{
  jQuery("textarea#uniqueId").bind("click change keypress", function(e){
      ....
      ....
  });
}

Or if the element is exists in page then write your code in document ready function like,

$(function(){
  jQuery("textarea#uniqueId").bind("click change keypress", function(e){
      ....
      ....
  });
});

Also id must be unique if you id conflicts with other elements the you should specify element with id like textarea#uniqueid

Upvotes: 0

Related Questions