Reputation: 5195
In my code that I'm writing I have a dynamically created div with an input box and a button. When their events occurs they have similar function to do, but there are small differences. For example if the button was clicked find the siblings value which is the inputs value and remove the div and replace the div that includes a new input an a button, but if the user pressed enter to find $(this).val()
and do the same thing to the div, so the functions are similar. I want to combine these event handlers to the proper event that occur.
I want to do something like this:
$("body").on('click keypress' ,'button input', function(e){
I need the second parameter in the on()
because the button and input are created dynamically
If I do something like below the event handlers don't get attached to the newly created elements, I think.
$(document).ready(function() {
var counter = 0
function giveNew(el, i) {
$(el).remove()
$("body").append("<button class='go" + " " + i + "' >Go</button>")
}
$("body button, body input").on('click keypress', function(e) {
counter++;
var target = $(e.target);
if (target.is('button')) {
for (var i = 0; i < counter; i++) {
giveNew(this, i)
}
console.log($(this).attr("class"))
} else if (target.is('input')) {
if (e.which == 13) {
alert("input");
}
}
})
});
html:
<input class = "input"> <button class="go">Go</button>
Upvotes: 1
Views: 46
Reputation: 87233
Add comma between the elements to bind events on multiple elements
$("body").on('click keypress' ,'button, input', function(e) {
I'd recommend you to add a class to all the target elements and use that class to bind event.
Javascript:
$(document.body).on('click keypress', '.myClass', function(e) {
Html:
<input class ="input myClass" />
<button class="go myClass">Go</button>
Upvotes: 2