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");
}
});
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I am trying to create a simple list with the option to add and remove elements, but it seems there are some scope rules about the selectors that I couldn't find in the official documentation. My HTML, including the jQuery is as follows:
$(function() {
$("#add").click(function() {
let val = $("input").val();
if (val !== "") {
let ele = $("<li></li>").text(val);
ele.append("<button class='rem'>X</button>");
$("#mylist").append(ele);
$("input").val("");
// $(".rem").click(function(){
// $(this).parent().remove();
// });
};
});
$(".rem").click(function() {
$(this).parent().remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Add new item">
<button id="add">Add</button>
<ol id="mylist">
</ol>
The commented part is the part that is running properly, but the one that is outside of the click function for the #add element is not working.
When you call $(".rem").click(.. jQuery will look for elements with class ".rem" and bind this new click event.
However, this only happens once. If you add elements later with the same class, those don't automatically get that event.
So what you'll want to do is bind this event to the new element you created, after you created it.
Lets clean this up:
<script>
function onAddClick() {
let val = $("input").val();
if (val !== ""){
let ele = $("<li></li>").text(val);
ele.click(onRemClick); <--- HERE
ele.append("<button class='rem'>X</button>");
$("#mylist").append(ele);
$("input").val("");
};
}
function onRemClick() {
$(this).parent().remove();
}
$(function() {
$("#add").click(onAddClick);
});
</script>
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");
});
This question already has answers here:
Getting the ID of the element that fired an event
(24 answers)
Closed 6 years ago.
I'd like to get the id of the clicked link with jQuery. Why does this return Undefined instead?
test = function(e) {
alert($(e).attr('id'));
return false;
}
$('.bleu').click(test)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
azeaze12
azeaze13
azeaze14
replace e with this, e refers to event object.
alert($(this).attr('id'));
or even better
$('.bleu').click(function(e) {
alert($(this).attr('id'));
return false;
})
You need to use this it refers to the clicked dom element, first parameter in click event handler is event object
test = function(e) {
alert($(this).attr('id'));
return false;
}
$('.bleu').click(test)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
azeaze12
azeaze13
azeaze14
Use this, and use .prop for id or simply this.id:
test = function(e) {
alert(this.id);
return false;
}
$('.bleu').click(test);
Alternative if the context is bound on the function, eg while binding events on Backbone views, you can use event.currentTarget, consider this:
$(el).click(function(event) {
console.log(this) // { "my": "context" }
console.log(event.currentTarget); // [DOMElement]
}.bind({
my: 'context'
}));
Use click event and use attr to get id. Try this:
$(".bleu").click(function(e) {
alert($(this).attr("id");
});
User this keyword
<script>
test = function(e) {
debugger;
alert($(this).attr('id'));
return false;
}
$('.bleu').click(test)
</script>
This question already has answers here:
Show/hide 'div' using JavaScript
(15 answers)
Closed 6 years ago.
I have a Checkbox in my index.html file as
#Html.CheckBoxFor(m=>m.isChecked, new { id = "isChecked" })
<div id='Shipping'>
<p> Some textboxes here </p>
</div>
I would like to hide the sipping div if the checkbox is checked and unhide if not checked. And i would like it to be dynamic. How do i do that?
I guess you'd first bind to the check box's change event:
$('#isChecked').change(function() {
//...
});
Within that event handler, you'd then show/hide the div based on the state of the check box. Possibly something like this:
if ($(this).is(':checked')) {
$('#Shipping').show();
} else {
$('#Shipping').hide();
}
Of course, you'll also want to set an initial value. A simple way to accomplish both would likely be to wrap the logic in a function:
var toggleDiv = function () {
if ($('#isChecked').is(':checked')) {
$('#Shipping').show();
} else {
$('#Shipping').hide();
}
}
Then call it from the event handler above:
$('#isChecked').change(toggleDiv);
And also when the page loads:
toggleDiv();
You just need to bind a change event to the checkbox and check it's :checked selector to determine if the div needs to shown or hidden.
<script>
$().ready(function(){
$('#isChecked').change(function()
{
$(this).is(":checked") ? $("#Shipping").show() : $("#Shipping").hide();
}).change(); // optional
});
</script>
javascript:
$('#isChecked').change(function(){
if($(this).is(":checked")) {
$(this).removeClass("hide");
} else {
$(this).addClass("hide");
}
});
css:
.hide{ display:none;}
HTML:
<div id='Shipping' class='hide'> </div>
$('#isChecked').change(function(){
if($(this).is(":checked")) {
$("#Shipping").hide()
} else {
$("#Shipping").show()
}
});
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;
});
});