Fire button click event when there are multiple classes on an element - javascript

How would I fire a button click event when a particular button is pressed (in this case the accept button).
I've tried the following but with little success:
Javascript
$('.notification-expand .Request .active-item > .accept-button').click(function () {
alert("hello");
});
HTML
<div class="notification-expand Request active-item" style="display: block;">
<div class="notification-body"></div>
<br>
<p>
<button type="button" class="btn btn-success accept-button btn-sm">Accept</button>
</p>
<div class="row">
<div class="col-xs-6 expand-col">
<button type="button" class="btn btn-warning barter-button btn-sm">Barter</button>
</div>
<div class="col-xs-6 expand-col">
<button type="button" class="btn btn-danger reject-button btn-sm">Reject</button>
</div>
</div>
</div>
Fiddle here

You have error in your selector , it should look like this:
$('.notification-expand.Request.active-item .accept-button').click(function () {
alert("hello");
});

You need to concatenate all classes without spaces to catch your target button
$('button.accept-button', '.notification-expand.Request.active-item').click(function () {
alert("hello");
});
See the updated snippet
Notice the syntax of ".className1.className2" instead of ".className1 .className2"

should be something like:
$('button.accept-button').click(function(){ ... });
there is really no need to go down the whole list if this is the whole code
----edit----
so when there are more items but only 1 active(i guess) then just target the active-item class:
$('div.active-item button.accept-button').click(function(){ ... });

try
$('.accept-button', $('.notification-expand.active-item')).click(function () {
alert("hello");
});
or
$('.notification-expand.active-item')).find('.accept-button').click(function () {
alert("hello");
});

Just give the button an id and reference back to that.
HTML
<button id="btnSubmitData"> Ok Button </button>
JQuery Code
$('#btnSubmitData').click(function(){ ... });
You can also have multiple button Ids bind to the same event:
$('#btnAccept, #btnReject, #btnWarning').click(function () {
alert("hello");
});
Take a look at the updated Working Fiddle.

Related

Button inside a form is not accessible

I'm trying to trigger the click event of a button inside a form using jQuery.
$(".switchLang").on("click", function(e) {
console.log("Clicked!")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-inline" action="">
<button type="button" class="btn mr-3 btn-link transparent switchLang">${{index.keys.lng}}$</button>
<button type="button" class="btn mr-3 btn-outline-light">${{index.keys.login}}$</button>
<button type="button" class="btn btn-primary">${{index.keys.getStarted}}$</button>
</form>
The function above is not invoked!
After research, I tried many solution but nothing's work. Like adding e.preventDefault(); inside the function also remove .click and replaced with .on and so on, but nothing works!
I have referred to this question: here.
Thanks.
Solved
I double checked my code. the html is written inside script of type text/template and this template is rendered before the jquery code. Thanks.
You could try
$(document).on("click",".switchLang",function (e) {
console.log("Clicked!")
});
Try this might help
$(document).on('click', '.switchLang', function (e) {
console.log("Clicked!")
});
You need to wait for the document to be ready before adding the click handler, like so:
$(document).ready(function () {
$('.switchLang').on('click', function (e) {
console.log("Clicked!")
});
});

Different values for innerHTML in debug and console log

I'm encountering a typical situation while accessing the innerHTML property using jQuery. I've fetched the target button using the jQuery attribute selector.
Below is the snippet of jQuery attribute selector.
jQuery('button[type="button"][class="btn btn-primary"]').each(function () {
var btn = jQuery(this);
console.log(btn);
if (btn[0].innerHTML === "OK") {
console.log("ok");
jQuery(this).click();
}
});
Following is the screenshot of the console log of the target button. It's innerHTML property is set to OK.
Following is the screenshot of the value of the innerHTML while debugging the target button object. In this case the value is "".
Ideally, the values of the innerHTML should be the same for both the cases.
EDIT
Why does this behavior differ that the ideal one? For both of the cases, the value of the innerHTML should be the same.
Also, there were multiple buttons. I have taken screenshots of different buttons. Thus their ID's are different. But still, the behavior is same.
Try something like this.
function SomeEvent($ele) {
alert($ele.html());
return false;
}
function invokeBtnEvents() {
$("[data-action=some-event]").off(); // clear old events
$("[data-action=some-event]").on("click", function() {
var $this = $(this);
return SomeEvent($this);
}) // define event(s)
return false;
}
$(document).ready(function() {
invokeBtnEvents();
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-12">
<br />
<button data-action="some-event" class="btn btn-primary">Button 1</button>
<button data-action="some-event" class="btn btn-primary">Button 2</button>
<button data-action="some-event" class="btn btn-primary">Button 3</button>
<button data-action="some-event" class="btn btn-primary">Button 4</button>
</div>
</div>
</div>
Your issue
What you are doing that I think is your main issue is the $.each() method.
Store the buttons in a variable,
let $button = $("button"); // this returns an array of all the buttons on the DOM
You can then use the $.each() method to get the clicked element
$.each($button, function(index, btn){
const $this = $(btn);
$this.off();
$this.click(function(){someEvent($this)});
});
I would not invoke button clicks like this because every time you click a button, this each loop gets ran. It will then send all of the buttons to that action unless you parse by an ID or something (you are using the innerText).
If you use the code in my snippet, only the clicked button will be triggered.
An alternative approach to my first snippet is using something like a dispatcher.
function DoActionOneClick($ele){
alert("Action 1 " + $ele.html());
}
function DoDefaultClick($ele){
alert("Default Action " + $ele.html());
}
function DispatchEvent(action, $ele){
switch(action){
case "some-event-1":
DoActionOneClick($ele);
break;
default:
DoDefaultClick($ele);
break;
}
}
function invokeActions(){
$("[data-action]").off();
$("[data-action]").on("click", function(){
// get this
var $this = $(this);
// get action
var action = $this.data().action;
DispatchEvent(action, $this);
});
}
$(document).ready(function(){
invokeActions();
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-12">
<br />
<button data-action="some-event-1" class="btn btn-primary">Button 1</button>
<button data-action="some-event-2" class="btn btn-primary">Button 2</button>
<button data-action="some-event-2" class="btn btn-primary">Button 3</button>
<button data-action="some-event-2" class="btn btn-primary">Button 4</button>
</div>
</div>
</div>

Trying to make a button in JavaScript but it's not working

I'm new in JavaScript and I took an app here to learn how to use the language.
So, In my index.html I have this code here:
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore">Reset</button>
<script type="text/javascript">
function reset() {
localStorage.setItem('total_win', 0);
localStorage.setItem('total_lose', 0);
}
</script>
</div>
and this as footer:
`<div id="scores" class="ui-grid-b">
<div class="ui-block-a">Tries left:<span id="tries_left">4</span></div>
<div class="ui-block-b">Total win:<span id="total_win">0</span></div>
<div class="ui-block-c">Total lost:<span id="total_lose">0</span></div>
</div>`
What I'm basically trying to do is just reset the score to zero. But It's not working...
I tried to put some alert() inside reset() function but didn't work also.
Does someone has a clue why this is happening?
Thanks for helping!
Use onclick property:
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore" onclick="reset()">Reset</button>
<script type="text/javascript">
function reset() {
localStorage.setItem('total_win', 0);
localStorage.setItem('total_lose', 0);
}
</script>
</div>
You are declaring the function but not calling it anywhere. So you need to call the function at onclick event of button.
You should add an event listener for the click event.
Because of your comment, you can change the DOM by changing the inner HTML, see below snippet and code:
document.getElementById('resetscore').addEventListener('click',function() {
//localStorage.setItem('total_win', 0);
//localStorage.setItem('total_lose', 0);
document.getElementById('total_win').innerHTML = 0;
document.getElementById('total_lose').innerHTML = 0;
});
document.getElementById('win').addEventListener('click',function(){
var a = parseFloat(document.getElementById('total_win').innerHTML);
document.getElementById('total_win').innerHTML = (a+1).toFixed(0);
});
document.getElementById('loss').addEventListener('click',function(){
var b = parseFloat(document.getElementById('total_lose').innerHTML);
document.getElementById('total_lose').innerHTML = (b+1).toFixed(0);
});
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore">Reset</button>
<button type="button" id="win">+1 Win</button>
<button type="button" id="loss">+1 Loss</button>
</div>
<div id="scores" class="ui-grid-b">
<div class="ui-block-a">Tries left:<span id="tries_left">4</span></div>
<div class="ui-block-b">Total win:<span id="total_win">0</span></div>
<div class="ui-block-c">Total lost:<span id="total_lose">0</span></div>
</div>
your script tag can't be inside a div. You need to move all your javascript to the end of your body, right before its closing tag, after all the html
Just add this:
<button type="button" onclick="reset()" id="resetscore">
You need to tell which one of your functions to use, notice the onclick, it does just that, so reset executes on click
Your button needs to call reset
<button type="button" id="resetscore" onclick="reset()">Reset</button>

ng-click no longer calls function after different dom element removed

Whenever I remove a dom element that precedes an element that has a ng-click attribute specified, it will no longer call the function that the ng-click references.
Here is an example of it not working. Note: if you change if(true) to if(false) and click save it will properly call the function.
function MainCtrl($scope) {
$scope.submit = function() {
alert('submitted');
}
function load() {
if(true){
$('#resetPassword').remove();
}
}
load();
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app>
<div ng-controller="MainCtrl">
<div class="btn-group m-b-20 pull-right" role="group">
<button type="button" id="resetPassword" class="btn btn-success">Reset Password</button>
<button type="button" class="btn btn-success" ng-click="submit();">Save</button>
</div>
</div>
</div>
I don't know why this is happening, but you should not use jQuery. Use ng-if to add or remove the button on condition. That's the way to go with Angular. jQuery's remove here looks dirty. ng-show just show or hides, but ng-if adds or removes the element from the DOM. It's what you want, and by far the simplest solution.
You should try to accomplish this with a custom directive. E.g:
JS
app.directive("removeClick", function() {
return {
link:function(scope,element,attrs)
{
element.bind("click",function() {
element.remove();
});
}
}
});
HTML
<div ng-app>
<div ng-controller="MainCtrl">
<div class="btn-group m-b-20 pull-right" role="group">
<button type="button" id="resetPassword"class="btn btn-success">Reset Password</button>
<button remove-click type="button" class="btn btn-success" ng-click="submit();">Save</button>
</div>
</div>
</div>
You are free to use getElementbyId at this point, although you should probably try to pass the correct element to your directive. This will probably give you a basic understanding of angular directives.
https://docs.angularjs.org/guide/directive

On button click, select a sibling element with JQuery

I have this code:
<div class="item">
<div class="hidden">44</div>
<input type="submit" id="btnAddCommentForAnswer" value="Add Comment" />
<script type="text/javascript">
$(document).ready(function () {
$('#btnAddCommentForAnswer').click(function () {
alert(XXX);
});
});
</script>
</div>
<div class="item">
<div class="hidden">12</div>
<input type="submit" id="btnAddCommentForAnswer" value="Add Comment" />
<script type="text/javascript">
$(document).ready(function () {
$('#btnAddCommentForAnswer').click(function () {
alert(XXX)
});
});
</script>
</div>
what code should I put at XXX to get the content of the div with class=hidden when i press the button at the same div with class=item?
If you click the first button you should get 44, and for clicking the second button you get 12.
id's are meant to be unique; you may wish to consider changing the id to a class.
With that in place, you could use a script like the following to achieve what you want:
$(document).ready(function() {
$('.btnAddCommentForAnswer').click(function() {
alert($(this).siblings('.hidden').text());
});
});
Here's a JSFiddle example: JSFiddle
Also, you don't need to have two script tags in your script! This one script wrapped in <script> tags is all that is necessary :)
Haven't tried but this should work:
$(this).closest('div').text()
You need not repeat the javascript code multiple times. Also, you cannot use id in jquery as the buttons have same id.
Here is the jsfiddle http://jsfiddle.net/t8XJZ/ which might solve your problem.
maybe this is more useful for you...
jquery:
$(document).ready(function () {
$('.item').each(function(){
$(this).find("#btnAddCommentForAnswer").click(function () {
alert($(this).prev(".hidden").text())
});
});
});
html:
<div class="item">
<div class="hidden">44</div>
<input type="submit" id="btnAddCommentForAnswer" value="Add Comment" />
</div>
<div class="item">
<div class="hidden">12</div>
<input type="submit" id="btnAddCommentForAnswer" value="Add Comment" />
</div>

Categories