Reputation: 1042
I'm experiencing an frustrating problem. I want to add an on-click event on an dynamically added input but I've been struggling with that for some time.
To show some code, here is my initial view
<div class="js-item-list"></div>
The user can then dynamically add data, this div is then populated for example like this (with initial divs)
<div class="js-item-list">
<div class="js-service-list-item>
<table>
<tr>
<td>Something</td>
<td><input type="text" class="js-consumption"></td>
</tr>
</table>
</div>
<div class="js-service-list-item>
<table>
<tr>
<td>Something</td>
<td><input type="text" class="js-consumption"></td>
</tr>
</table>
</div>
... and so on ...
</div>
I want to add an on-click event with jQuery to all the inputs so that when the users clicks on the input, all of the content of that specific input box would be selected. But I have no idea how to so all suggestions would be greatly appreciated, thanx :)
Upvotes: 0
Views: 72
Reputation: 20455
You can use delegate method for newly added or future elements
$('.js-item-list').delegate('input', 'click', function(e) {
//some code here
})
or for newer version >1.7 of jquery you should use .on()
As of jQuery 1.7, .delegate() has been superseded by the .on() method
$('.js-item-list').on('input', 'click', function(e) {
//some code here
})
Upvotes: 2
Reputation: 1443
You can use Jquery .on function, which work on dynamically added html element.
$(".js-item-list").on( "click", ".js-consumption" ,function() {
alert( $( this ).val() );
});
.js-item-list is the selector class which is not change dynamically only inner element of this will be change.
Upvotes: 1
Reputation: 2929
Use the jQuery's event delegate function may resolve your problem, try this :
$(".js-item-list").on("click" , "input.js-consumption" , function(){
var domInput = this ;
var $input = $(this) ;
var value = $input.val();
// to do
});
Upvotes: 1
Reputation: 509
I'm assuming you have some button that the user clicks to add another "Something". I'm also assuming you have somewhere in your JS code $(".js-service-list-item").onclick(someAction)
.
That initial JS code only applies to the elements with that class that exist at the time it is run. This means every time they add an element to the list, you need to reapply that onclick method.
So what I would do is move that $(".js-service-list-item").onclick(someAction)
code into the onclick function you have for the button that adds these service-list-items. That way each time you create a new element, you'll also register the onclick event with it
Upvotes: 0