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>
Related
This question already has answers here:
onClick to get the ID of the clicked button
(18 answers)
Closed 2 years ago.
I am currently working on a project in Javascript.
I would like to know how to get the ID of a element with a click.
This is my code:
const cercleEl = document.querySelectorAll(".cercle");
cercleEl.forEach((element) => {
const elementId = element.getAttribute("id");
});
document.addEventListener("click", cercleEl);
You can do it like this:
document.addEventListener('click', (ev)=>{
console.log(ev.target.id)
});
ev.target is the element you click on. Thus, you can easily find it's id by using ev.target.id. There is no need to create a list of all elements ID's at the start.
You can try like this. You need to add ,addEventListener to Particular elements in forEach loop
const cercleEl = document.querySelectorAll(".cercle");
cercleEl.forEach((element) => {
element.addEventListener("click", function() {
console.log(this.getAttribute("id"))
});
});
<div class="cercle" id="a">
<h1>hi</h1>
</div>
<div class="cercle" id="b">
<h1>hello</h1>
</div>
document.querySelectorAll('.circle').forEach(function(element) {
element.addEventListener('click', () => {
console.log(element.id);
});
});
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");
}
});
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:
How to have click event ONLY fire on parent DIV, not children?
(12 answers)
Closed 8 years ago.
I'm looking for a jquery function doing the following :
if I click everywhere inside the div (but elements inside this div), the code is executed .
if I click in an html element inside this div , noting happens .
You need to test if the clicked target is this. Fiddle here: http://jsfiddle.net/ZBC43/
$('div').on('click', function(e) {
if (e.target !== this) return;
alert('div clicked');
});
The event is lopped through the element, until a element with a click element is found.
Solutions:
Test if the target element is the same as the delegateTarget
You set the event of the inner elements to a empty function
You need something like this (i try to find parent div with your class):
<div class='foobar'>
<span>child1</span>
<span>child2</span>
</div>
<span>child3</span>
<script>
$('.foobar').on('click', function(e) {
var testelem = $(e.target);
while (testelem != undefined && !testelem.hasClass('foobar')){
testelem = testelem.parent();
}
if (testelem != undefined && testelem.hasClass('foobar')) {
alert('code');
}
});
</script>
http://jsfiddle.net/eaVzx/
You can use tagName dom property to get current target element name.
TagName: Returns the name of the element.
HTML
<div id="myDiv" style='display:inline-block; width:300px;'><span style='display:inline-block;'>Hello Click here</span><br /><span style='display:inline-block;'>Click here</span></div>
Javascript
$(document).ready(function(){
$('#myDiv').click(function (e) {
if (e.target.tagName == "DIV") {
alert('Clicked on Div');
}
else{
alert('Clicked on Inner Element');
}
});
});
Try in fiddle
OR also use nodeName property to get current element.
NodeName: Returns the name of the current node as a string.
Try in fiddle 2
Try this:
$("div").click(function(e) {
if (e.target !== this) return;
alert("inside a div");
});