user2952265
user2952265

Reputation: 1630

jQuery - get ID of element after paste event

After pasting text, I want to get the ID of the target div. Later the divs are generated dynamically, code does not work:

js fiddle

HTML

<div class="wrap">

<div class="entry" id="1" contenteditable="true">paste here</div>
<div class="entry" id="2" contenteditable="true">paste here</div>
<div class="entry" id="3" contenteditable="true">paste here</div>
<div class="entry" id="4" contenteditable="true">paste here</div>

 </div>

JS

$('.wrap').on("paste", function(){

    console.log("current box ID: " + $(this).attr("id") );
});

Upvotes: 0

Views: 952

Answers (6)

Claudio Redi
Claudio Redi

Reputation: 68440

Not sure why you're attaching the event against the "container". I believe you have 2 options

$('.wrap').on("paste", function(e){

    console.log("current box ID: " + e.target.id );
});

or

$('.entry').on("paste", function(e){

    console.log("current box ID: " + this.id );
});

I'd go with the second option since it's more more clear to attach the event direclty to relevant elements instead of doing it to the container and use the e.target approach.

Upvotes: 3

bobthedeveloper
bobthedeveloper

Reputation: 3783

Because you binded the 'paste' event on the wrap class (which doesn't got an attribute id) you get a NULL.

You have to bind it you your entry fields, which have the id attribute.

$('.wrap .entry').on("paste", function(){
    console.log("current box ID: " + $(this).attr("id") );
});

Upvotes: 1

Jay Blanchard
Jay Blanchard

Reputation: 34426

I'd go with this (just a little less code, but not much -

$('.entry').on("paste", function(e){
    console.log("current box ID: " + this.id ); // this.id is all you need to get any current id
});

Upvotes: 1

squid314
squid314

Reputation: 1395

You need to look at the target of the event (which is where the event originated) and then find the .entry which wraps that. You can't necessarily look directly at the target if you want to support having any complex structure inside of the .entry elements.

$('.wrap').on('paste', function(event){
  console.log('paste id: ' + $(event.target).closest('.entry').attr('id'));
});

Upvotes: 3

Ortiga
Ortiga

Reputation: 8824

You are binding the event to the wrap div, so that's what this means for in the callback.

Change your event binding to:

$('.wrap .entry').on("paste", function(){
    console.log("current box ID: " + $(this).attr("id") );
});

Upvotes: 1

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

Try you're using parent class.wrap You need to use .entry class as you are pasting in that div

$('.wrap div.entry').on("paste", function(){   
    console.log("current box ID: " + $(this).attr("id") );
});

If .entry is created dynamically then you can use event delegation

$(document.body).on('paste','.wrap .entry',function(){
    console.log("current box ID: " + $(this).attr("id") );
});

Fiddle

Upvotes: 6

Related Questions