JQuery Trigger Event on Dynamically added elements programmatically - javascript

I can successfully bind an event to dynamically added elements, but I have a problem triggering it on its first load programmatically.
$('body').on('change', '#elem', function () {
console.log('bind event success');
});
I tried these codes below but do not work.
Not working
$('body').trigger('change');
Not working
$('body').on('change', '#elem', function () {
console.log('hello world');
}).change();

You can trigger an event on the DOM element #elem directly, as you can see here:
$('body').on('change', '#elem', function () {
console.log('new value is: '+this.value);
});
$("button").click(function(){$("#elem").val("3").change()})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="elem"><option>1</option><option>2</option><option>3</option></select>
<button>trigger change to 3</button>

Related

How to handle events on dynamically added elements in jQuery

A fairly straightforward question - Why doesn't mouseover trigger for (text) inputs which are dynamically generated after the page has loaded?
I can get it to work for checkbox, select, textarea...
Below code doesn't give an event
$(document).ready(function () {
$(`input[type=text]`).on(`mouseover`, function (e) {
console.log(e);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text">
Below code gives an event for everything but text input:
$(document).ready(function () {
$(`input, textarea, [type=checkbox], select`).on(`mouseover`, function (e) {
console.log(e);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input>
<textarea></textarea>
<input type="checkbox">
<select>
<option>test</option>
</select>
How can I trigger mouseover event for a text input?
EDIT: The text inputs are dynamically generated after the document has loaded.
Thank you
You need to pass a second parameter to .on that allows for event delegation:
$(document).ready(function () {
// Set the handler up on something you know will be there from the start
// that the event(s) that get triggered later can "bubble" up to. That's
// document in this case.
// The second argument becomes what you want the event to be handled on
$(document).on(`mouseover`, "input[type='text']", function (e) {
console.log(e);
});
// Create a new element after the handler has been set up
$(document.body).append('<input type="text">');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Trigger button click event programmatically using JavaScript or jQuery on page load in Internet Explorer

I have this piece of code
window.onload = function () {
$('#btnFilter').click(function (e) {
btnFilter(e);
});
}
The function works on button click but I need that the button is clicked when the page opens. I've tried things like $('#btnFilter').trigger( "click" ); but the button still not clicked on page opening. How can I achieve this thing? I can't just call the function because I get the error "Cannot read property 'currentTarget' of undefined" beacuse I don't give any event as parameter.
function btnFilter(e) {
element = e.currentTarget.parentElement;
//other code
}
You can try like this:
$(document).ready(function(){
$('#btnFilter').trigger('click');
});
$(document).on('click','#btnFilter',function(e){
btnFilter(e);
});
function btnFilter(e)
{
element = e.currentTarget.parentElement;
}
You can change your 'btnFilter' to accept the button instead of the event:
function btnFilter(element) {
element = element.parentElement;
...
}
$(function() {
$("#btnFilter").click(function(e) { btnFilter(this); return false; });
// Pass the button to the filter operation on load
btnFilter($("#btnFilter")[0]);
});
alternatively, accept the parent element directly
$(function() {
$("#btnFilter").click(function(e) { btnFilter(this.parentElement); return false; });
// Pass the button parent to the filter operation on load
btnFilter($("#btnFilter")[0].parentElement);
});
If you use jquery i would keep it coherent and not mix it with vanilla javascript. A Jquery solution is:
$(document).on("click", "#btnFilter", btnFilter);
$(document).ready(function(){$("#btnFilter").click()});
or
$(document).on("click", "#btnFilter", btnFilter);
$(document).ready(btnFilter);
In you solution the error is the event binding: when you bind the event to #btnFilter on page load, the element is not existing yet, so the function cannot be triggered.
jQuery Solution:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").trigger("click");
});
</script>
</head>
<body>
<button onclick="alert('clicked')">Click</button>
</body>
</html>

What event does jQuery fire when using append on a textarea?

I'm trying to monitor for any changes in a textarea:
<textarea id="log-box__data"></textarea>
Changes are made to the textarea exclusively via jQuery append:
$(document).on('click', '#myBtn', function(e) {
$('#log-box__data').append('someText' + '\n');
});
What event is fired whenever something is append[ed] to the textarea?
And, if there isn't one, how can I monitor for this change?
Things I've Tried:
$(document).on('input change keyup paste', '#log-box__data', function() {
alert( "foobar" );
});
None of those events fire when #myBtn is clicked.
Using trigger function after append will help
$(document).on('click', '#myBtn', function(e) {
$('#log-box__data').append('someText' + '\n');
$('#log-box__data').trigger("change");
});
$('#log-box__data').on('change', function(e) {
alert( "foobar" );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="log-box__data"></textarea><br />
<button id="myBtn">add text</button>
append is not a good idea and also set a value will never call the onchange event so try below code to trigger manually
$("#myBtn").bind("click",function(){
$("#log-box__data").val("yourtexthere").trigger('change');
});

How to modify clickable elements in jQuery?

Why doesn't the on click listener work after clicking on the first list-button?
JSFiddle link
$(".acceptTask").on("click", function(){
acceptTask(this);
});
$(".solveTask").on("click", function() {
solveTask(this);
});
function solveTask(e){
...
}
function acceptTask(e){
...
$(document).on("click", ".solveTask", solveTask);
}
$('.solveTask').on('click', /*...*/) only applies the event handler to anything that has a class "solveTask" at that time. So when you add the solveTask class in your acceptTask function, add an event listener.
$(e).addClass('btn-warning solveTask')
.click(function () { solveTask(this); });
See fiddle: https://jsfiddle.net/1203y34b/1/
I had this problem previously and used 'delegate' instead of 'on':
$(document).delegate('.solveTask', 'click', solveTask)

Why does jQuery not register my <a> click?

In the example below
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
test
<button id="btn-add">Add</button>
<div id="placeholder">
</div>
<script type="text/javascript">
$(document).ready(function () {
$('a').on('click', function () {
alert('clicked');
});
$("#btn-add").on("click", function () {
$('#placeholder').prepend('<a href=\'#\'>blah2</a>');
});
});
</script>
</body>
</html>
If you click on 'Add' then 'blah2' nothing happens even though I am trying to alert on any anchor click. As a check if you click on 'test'you get the popup
Try this instead:
$('body').on("click", "a", function () {
alert('clicked');
});
Link to fiddle
Since the element is generated dynamically, you need to use delegation with the on() method or create a literal jQuery object and add a click event.
$('closestParent').on('click', 'a', function(){ ... })
// OR
var $link = $('<a href=\'#\'>blah2</a>').click(function(){ ... })
$link.prependTo('#placeholder')
Its because you need to delegate the click to a parent element. If you are using 1.7+ use .on or if you are using 1.6 and lower you can use .delegate(). The element doesn't exist when the dom is ready so you need to delegate the event to a parent element. Meaning you can use $(document) or use any parent element that is already there
$(document).on("click","a", function () { //<-- this allows for the event to bubble up to the document in this case
alert('clicked');
});
$(document).delegate("a","click", function () {
alert('clicked');
});

Categories

Resources