Event in jQuery .html() won't detect [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I'm trying to use a button that is printed by .html(). I've tried .find() after searching through this site but the onclick event still seem not detected.
<div id = "div4html">div</div>
<button id="printbtn">printbtn</button>
<script>
$("#printbtn").on( "click", function() {
$("#div4html").html('<button id ="btntest">btntest</button>');
});
$("#div4html").find("#btntest").on( "click", function() {
alert("on click");
});
</script>
while the #btntest onclick doesn't show an alert, the CSS on #btntest works.
There is something I don't know about elements that are created dynamically?

You can't do this because js don't even for events in newly created content by default.
Here is the way to do it :
$("#div4html").on('click', "#btntest" , function() {
// Your code
}

You need to do:-$("#div4html").on( "click", "#btntest", function() {
It's called:- Event Delegation
Example:-
$("#printbtn").on( "click", function() {
$("#div4html").html('<button id ="btntest">btntest</button>');
});
$("#div4html").on( "click","#btntest", function() {
alert("on click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "div4html">div</div><br>
<button id="printbtn">printbtn</button>

Delegate the event from the body
$("body").on( "click",'#btntest', function() {
alert("on click");
});

Related

Attach attribute [data-name] then click using this data attribute [duplicate]

This question already has answers here:
Direct vs. Delegated - jQuery .on()
(6 answers)
Closed 4 years ago.
I'm trying to add a data-name attribute on clicking one element and then when that element is clicked do something else.
$(".btn01").on("click", function() {
$(".next").attr("data-name", "btn02");
});
$("[data-name='btn02']").on("click", function() {
console.log("I clicked this button");
});
It is updating in the DOM but not working?
Any ideas?
You must use event delegation since the attribute you're using in the selector of the second click event [data-name='btn02'] is created dynamically by the JS code:
$(".btn01").on("click", function() {
$(".next").attr("data-name", "btn02");
});
$("body").on("click", "[data-name='btn02']", function() {
console.log("I clicked this button");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn01">CLICK ME then click the span bellow</button>
<br><br>
<span class="next">Next span</span>
Try the following, use event delegation for attaching event to "[data-name='btn02']", as $("[data-name='btn02']") element will not exist till $(".btn01") is clicked.
$(".btn01").on("click", function() {
$(".next").attr("data-name", "btn02");
});
$(document).on("click", "[data-name='btn02']", function() {
console.log("I clicked this button");
});
If you are just trying to make it so the first button needs to be clicked before the second can, you can just use a boolean variable for that:
var firstButtonClicked = false;
$(".btn01").on("click", function() {
firstButtonClicked = true;
});
// the second button
$(".next").on("click", function() {
if (firstButtonClicked == true) {
console.log("I clicked this button after the first one");
}
});

JQuery - Changing element id isn't working [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
jQuery click event not working after adding class
(7 answers)
Closed 5 years ago.
I am trying to change the functionality of a button by changing its ID dynamically.
<srcipt>
$("#old-id").click(function func_P(){
//Some code
this.id = "new-id";
});
$("#new-id").click(function func_Q(){
// some other code
});
$("#clear").click(function func_R(){
$(".in").attr("id","new-id");
});
</script>
<body>
<button id="old-id" class="in">Button A</button>
<button id="clear">Clear</button>
</body>
But the problem I am facing is that when I click "Button A" the id gets changed but when I click "Button A" again func_P() is executed again instead I intend to call func_Q.
Use .on function to bind (live) click.
$("#old-id").on('click', function func_P(e) {
//Some code
if (this.id == "old-id") {
this.id = "new-id";
console.log('old id clicked');
e.stopPropagation()
}
});
$(document).on('click', "#new-id", function func_Q() {
// some other code
console.log('new id clicked');
});
$("#clear").on('click', function func_R() {
$(".in").attr("id", "old-id");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="old-id" class="in">Button A</button>
<button id="clear">Clear</button>
And if you want to clear id, you should change:
$(".in").attr("id","new-id");
To:
$(".in").attr("id", "old-id");

jquery create new buuton [duplicate]

This question already has answers here:
Event handler not working on dynamic content [duplicate]
(2 answers)
Closed 7 years ago.
I used the following codes to create a "New button" next to the "button". But, when I click the "New button", it cannot create another "New button". Why? I have defined the "click" event of "button" tag
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2jquery.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("body").append("<button type=button>New button</button>");
})
})
</script>
</head>
<body>
<button type="button">button</button>
</body>
Use event delegation for binding events automatically on dynamically added elements.
$(document).ready(function() {
var button = "<button type=button>New button</button>";
$(document).on('click', "button", function() {
$("body").append(button);
});
});
$(document).on('click', "button", function() {
$("body").append("<button type=button>New button</button>");
})

jQuery: Checked event on checkbox added later through innerHTML is not working. [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
There are two checkboxes in my page for which the change event I'm capturing in the below code:
$(':checkbox').change(function(){
alert('hello '+this.checked);
});
But if I add third checkbox to that group and I click this checkbox, the above function is not triggered.
I am adding the third checkbox to the group through the innerhtml code like below:
var text2='<li><input type="checkbox" name="vehicle" value="TRUE"/> New function</li>';
text1=text1+' '+ text2;
parent.innerHTML=text1;
Note: text1 is the existing innerhtml code of existing two checkboxes.
Use event delegation. Use on method.
Attach an event handler function for one or more events to the selected elements.
$('document/ParentSelector').on('change', ':checkbox', function () {
alert('hello ' + this.checked);
});
Just update your parentSelector in the code above and it should work.
Docs: https://api.jquery.com/on
Use the .on() function of jQuery for run time added element:
$(document).on('change',':checkbox',function(){
alert('hello '+this.checked);
});
Use Event delegation in the context for adding dynamic created elements in the dom there are many examples in SO
$(document).on('change' , ':checkbox', function(){
alert('hello '+this.checked);
});
Important point here is when you are using .on to attache event as per the below code it attach event to both static and dynamically added control , so there is no need to of function you writtne on will do the work of attached function to all element(static or dynamic).
if you are adding checkbox at runtime i.e. after page get created than you need to use .on function of jquery to attache function
$( "input[type=checkbox]" ).on( "click", countChecked );
var countChecked = function() {
var n = $( "input:checked" ).length;
$( "div" ).text( n + (n === 1 ? " is" : " are") + " checked!" );
};
in simple you can do this
$('document').on("change", "input:checkbox", function() {
alert('hello '+this.checked);});
or try
$('input:checkbox').on('change', function () {
if (!this.checked) {
}
});
jsfiddle for this : http://jsfiddle.net/m77sN/112/

why not my jquery event called for dynamically generated span [duplicate]

This question already has answers here:
Events triggered by dynamically generated element are not captured by event handler
(5 answers)
Closed 9 years ago.
My JQuery Code is:
$(document).ready(function() {
$('#btnGenSpan').on('click', function(e) {
$("#div_container").html($("#div_container").html()+
"<span>Item-01 <a href='?delete=1' class='delete_item'>X</a></span><br />");
});
$('a.delete_item').on('click',function(e) {
alert('delete clicked');
return false;
});
});
Here is html content:
<input type="button" id="btnGenSpan" value="Generate More Item" /><br /><br />
<div id="div_container">
<span>Default Item-01 <a href='?delete=111' class='delete_item'>X</a></span><br />
<span>Default Item-02 <a href='?delete=112' class='delete_item'>X</a></span><br />
</div>
Here is the JSFiddle here
For static items(Default Item-01 & Default Item-02) X anchor works fine and called delete_item but for those span which are generated by jquery(same html class & anchor generated as default) not called. any help is highly appreciated.
You may want to try using event delegation syntax of on to have the event available for the dynamically created elements. Reason being your original event is bound only to the a.delete_item that already existed in DOM at the time of event binding, so newly added ones just did n't have that event bound to it. So bind the event to the parent container that exists in DOM as long as you need the event so that it gets delegated to the selector (jquery uses event bubbling to make this work) when that event happens.
$('#div_container').on('click','a.delete_item', function(e) {
e.preventDefault();
alert('delete clicked');
});
Demo
You must creat event for new DOM
Try this
$(document).ready(function() {
$('#btnGenSpan').on('click', function(e) {
$("#div_container").html($("#div_container").html()+"<span>Item-01 <a href='?delete=1' class='delete_item'>X</a</span><br />");
$('a.delete_item').on('click',function(e) {
alert('delete clicked');
return false;
});
});
$('a.delete_item').on('click',function(e) {
alert('delete clicked');
return false;
});
});

Categories