Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the event object for onClick()

Tags:

jquery

I have a loop which generates lot of input text fields with jquery. Now i want to fire stopPropagation method when someone clicks on those input tags. I am in a notion that this method works like this:

event.stopPropagation()

But problem is that i want to fire this method on onClick attribute of the input tag. Like this:

$(handler).html('<input type="text" value="'+text+'" style="width:280px;" onClick=stopPropagation(); />');

And this won't work for obvious reasons. I need to get the event object for this click. Whats the smarter way?

like image 342
beNerd Avatar asked Oct 27 '25 09:10

beNerd


1 Answers

Its easy, just add "event" key word to your onClick call, like so:

$(handler).html('<input type="text" value="'+text+'" style="width:280px;" 
    onClick=stopPropagation(event); />');

Then in your function:

function stopPropagation(event) { /* do work */ }

or you can do it the jQuery way:

$('input').on("click", function(event) { /* do work */ });

keep in mind, on your inline functions, just like the word this, event is a key word that tells the js your function should be getting an event argument

Finally you could just change the add all together:

var newInp = $("<input />").width(280).text(text);
$(handler).append(newInp);
newInp.on("click", function(e) { /* e is your event */ });
like image 163
SpYk3HH Avatar answered Oct 29 '25 05:10

SpYk3HH