getting the value of the button clicked in a group of buttons - javascript

html
<div id="group1">
<button>buttonA</button>
<button>buttonB</button>
</div>
javascript
$('#group1').on('click', function(event) {
// get ONLY the value of the button cilcked
});
Is something like this possible without attaching an event to every button in the group?

Add a target selector to the on() and use this or event.currentTarget within the handler function to access the matching element the event occurs on
$('#group1').on('click', 'button', function(event) {
console.log($(this).text())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="group1">
<button>buttonA</button>
<button>buttonB</button>
</div>

Related

Dynamically create button and then remove that button when clicked in jquery

lHi,
I have some divs in a html doc and when I click the div I am adding a button. eg attached:
HTML:
<div class="week">
<div class="day wk1" id="day1">
<label for="day1">Test</label>
</div>
<div class="day wk1" id="day2">
<label for="day2">Test</label>
</div>
When I add a button by clicking on the div, no problem.
Add Button:
$(".day").click(function (e) {
e.preventDefault();
var check = $("#day7").width() - 2;
var insert = $(this).prop("id");
insert = `#${insert}`;
var par = $('<br class="break"><button class="testing">').html('Shift Manual Insert').width(check).css("background-color", "green");
par.appendTo(insert);
// console.log(insert);
});
When I remove the button by clicking on it it does remove it but simultaneously adds a new button as per the code above and below.
Remove Button:
$(".day").on('click','.testing', function(e){
e.preventDefault();
$(".break").remove;
$(this).remove();
});
I am sure I am doing something silly but for the life of me, I cannot figure it out? Please ignore my incorrect use of id's and classes, this is purely a test to gain experience.
Any help will be most appreciated.
Kind regards
Wayne
The event is getting propagated from the click handler on dom with .testing class to it's parent that is dom with .day class. .day have another click handler which add the element.So after removing the element again $(".day").click(function(e) { is getting fired which is adding back the button element
Replacee.preventDefault(); with e.stopPropagation(); in the click handler of .testing
$(".day").click(function(e) {
console.log('x')
e.preventDefault();
var check = $("#day7").width() - 2;
var insert = $(this).prop("id");
insert = `#${insert}`;
var par = $('<br class="break"><button class="testing">').html('Shift Manual Insert').width(check).css("background-color", "green");
par.appendTo(insert);
// console.log(insert);
});
$(".day").on('click', '.testing', function(e) {
e.stopPropagation();
$(".break").remove;
$(this).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="week">
<div class="day wk1" id="day1">
<label for="day1">Test</label>
</div>
<div class="day wk1" id="day2">
<label for="day2">Test</label>
</div>
Your button is present inside the div. So when you click the button, your div click event is also fired. This is due to event bubbling. Check https://www.w3schools.com/jquery/event_stoppropagation.asp
$(".day").on('click','.testing', function(e){
e.stopPropagation();
e.preventDefault();
$(".break").remove;
$(this).remove();
});

How could i target a div and it's child to handle a click?

I have a <div class="stock"></div>wrapped around :
<div class="stockAdd"></div>
<div class="stockRemove"></div>
<div class="stockInput"></div>
I want to prevent a click inside my .stock to trigger a function. For now i have the following :
if ($(event.target).is('.stockInput') || $(event.target).is('.stockAdd') || $(event.target).is('.stockRemove')) {
console.log("Ajout stock");
return
}
Isn't there a better way to select thos three divs ? The $(event.target).is('.stock') don't get the job done when i click my nested divs.
Thanks
If I understand you correctly, you want to catch click events on .stockAdd, .stockRemove, and .stockInput, but not on other elements within .stock itself, is that correct?
If so, a delegated event can take care of that without any need to manually check the event target:
$('.stock').on('click', '.stockAdd, .stockRemove, .stockInput', function() {
alert("Clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stock">
<div class="stockAdd">stockAdd</div>
<div class="stockRemove">stockRemove</div>
<div class="stockInput">stockInput</div>
<div>No event</div>
</div>
I would strongly recommend against depending on event.target here; it's too fragile. Any HTML tags nested inside your desired targets would break things:
$('.stock').on('click', function(event) {
if (event.target.className=="stockAll") {
alert("clicked");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stock">
<div class="stockAll">
This <b> will not work if someone clicks in the bold area</b> but works outside
</div>
</div>
You can add a separate class to all of them like .stock-inner and then grab them all with $('.stock-inner') or you can use a $("div[class^='stock-inner']) - this will grab the parent .stock div...
Also, to reject a click event within the handler you're gunna want to use e.preventDefault() where e is the event object.
the reason it doesn't work well on nested divs is they pass the conditional if in your example, to make it stricter you could add div to selector:
if ($(event.target).is('div.stockInput') || $(event.target).is('div.stockAdd') || $(event.target).is('div.stockRemove'))
You can attach the event on .stock and then filter using the event.target.
HTML
<div class="stock" style="border: 10px solid #000;">
<div class="stockAdd">Add</div>
<div class="stockRemove">Remove</div>
<div class="stockInput">Input</div>
</div>
JavaScript
$('.stock').on('click', function(e) {
if( e.target.className !== 'stock' ) {
console.log(e.target.className);
}
});
jsfiddle

How can call the jquery function onclick only parent element [duplicate]

This question already has answers here:
How to stop events bubbling in jQuery? [duplicate]
(5 answers)
Closed 7 years ago.
I am trying to call a jQuery function when clicked only on parent element.
<div id="clcbox" class="click-img">
<img id="fire" onclick="createFirework()" src="img/clicker.png" />
</div>
I have an img tag inside a div. When I click on the div it should call one function and when I click on the img I want to call another function. How can I do this?
$('.click-img, .wishes').click(function () {
$('.flipWrapper').find('.card').toggleClass('flipped');
return false;
});
When I click the div I should call the above function. However now when I click on the image, it is also calling this function and createFirework().
The issue is due to event bubbling. If you attach your events in an unobtrusive manner you can easily stop this behaviour.
<div id="clcbox" class="click-img">
<img id="fire" src="img/clicker.png" />
</div>
$('#fire').click(function(e) {
e.stopPropagation();
createFirework();
});
$('.click-img, .wishes').click(function (e) {
$('.flipWrapper').find('.card').toggleClass('flipped');
e.preventDefault();
});
First off, don't mix inline (onclick) event handlers and jQuery event handlers. Once, you've got a jQuery event handler in place of your createFirework method, you simply stopPropagation to stop it calling the handler on the outer div.
Below is an example
$('.outer').click(function(e){
alert("You clicked text in the div");
});
$('.inner').click(function(e){
alert("You clicked the button, but the div event handler will not fire");
e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
<span>here is some text inside the div, click it</span>
<button class="inner">Click me</button>
</div>
You need to use stopPropagation function:
http://www.w3schools.com/jquery/event_stoppropagation.asp
In your case you need to add this on image click event:
$('.click-img, .wishes').click(function (event) {
event.stopPropagation();
$('.flipWrapper').find('.card').toggleClass('flipped');
return false;
});
It looks like you need to stop the click event from the image bubbling up the DOM chain.
$('.click-img, .wishes').click(function (e) {
$('.flipWrapper').find('.card').toggleClass('flipped');
e.stopPropagation();
});
When you click on the image, that event is passed up to it's parent, in this case the <div>. That is by behavior. To stop that from ocurring, you call the stopPropagation() function that is part of the incoming event argument for the click event.
You can use Event.stopPropagation(), to stop the click event bubble to its parents, but you also need to add a param event, so your function can access it without browser issue.
// VVVV pass `event` as createFirework's param.
<img id="fire" onclick="createFirework(event)" src="http://placehold.it/50x50" />
But I'd suggest that answers that separate js part and html part would be better. Just like Jamiec's.
function createFirework(event) {
console.log('inner');
event.stopPropagation();
}
$('.click-img, .wishes').click(function () {
console.log('outer');
return false;
});
#clcbox {
width: 100px;
height: 100px;
border: solid 1px black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clcbox" class="click-img">
<img id="fire" onclick="createFirework(event)" src="http://placehold.it/50x50" />
</div>

Find the id by class in nested div jquery

I have an html like this
<div class='click' id='1'>
one
<div class='click' id='2'>
two
<div class='click' id='3'>
three
<div class='click' id='4'>
four
<div class='click' id='5'>
five
</div>
</div>
</div>
</div>
if i have and click event on class click ,there is any way to return the id of which i click
such as
$('.click').click(function(){
alert('id whitch i click')
});
Becase if i click on three i allway get the id of one and two three.
Sure, just do this:
$('.click').click(function(e){ //e=event
alert($(this).attr("id")); // alert clicked element's id
e.stopPropagation(); // stop event propagation so it doesnt propagate to click 1 and click 2
})
Update: As mentioned by Felix Kling, you can access de DOM directly and use:
alert(this.id);
Demo: http://jsfiddle.net/tzJUN/ using this.id http://jsfiddle.net/c65x9/
If you keen : jQuery attr vs prop?
Stop propogation will stop the click event the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
API:
.stoppropagation - http://api.jquery.com/event.stoppropagation/
Code
$(document).ready(function () {
$('.click').click(function (event) {
event.stopPropagation();
alert($(this).prop("id")); //<< --- or this.id
});
});
$('.click').click(function(e){
$(this).attr("id");
alert($(this).attr("id"));//here you can see your clicked id
})
Yes. its simple
$(document).ready(function(){
$('.click').click(function(){
var ID=$(this).attr('id');
alert(ID);
//This ID varible will return ID of the Div Clicked
});
});

Delegate/Live Failure. Can't bind events after Prepending an element

EDIT--- I realized that the problem here was that the click handler that was bound to the element had to be unbound before I could bind another click handler handler.
I want to allow the user to select/unselect items by click on the element in question. The elements start in an "options" box and if clicked, move to a "selected box". If they are then clicked in the selected box, the elements move back to the original options box.
Can't figure out why delegate() and live() are not working here. I assume this has to do with prependTo() or appendTo().
$('#amen_options .options p').click(function(e){
$(this).appendTo('#amen_selected .options');
e.stopPropagation();
e.preventDefault();
});
/*
$("body").delegate('#amen_selected p', 'click', function(e){
#(this).appendTo('#amen_options .options');
e.stopPropagation();
e.preventDefault();
});
*/
$('div#amen_selected div.options p').live('click',function(e){
$(this).appendTo('#amen_options .options');
e.stopPropagation();
e.preventDefault();
});
Here's the markup:
<div>
<div id="amen_options">
<h3>Click to Select</h3>
<div class="options">
<p data-option="">One</p>
<p data-option="">Two</p>
<p data-option="">Etc...</p>
</div>
</div>
<div id="amen_selected">
<h3>Selected</h3>
<div class="options">
</div>
</div>
The first click works (sending p elements from options to selected box). Once in selected, though, no event handlers are binding. The firebug console isn't showing an error. Normally, I'd assume that this is a markup problem, but I've checked it repeatedly.
Thanks!
It looks like delegate() works good.
http://jsfiddle.net/fLXgU/1/
$('body').delegate('#amen_options .options p', 'click', function(e) {
$(this).appendTo('#amen_selected .options');
return false;
});
$('body').delegate('#amen_selected .options p', 'click', function(e) {
$(this).appendTo('#amen_options .options');
return false;
});

Categories

Resources