One function - many buttons - javascript

I have in HTML a button with id="button1".
We have JavaScript function:
$('#button1').click(function() { ... } );
It works well.
But what if we have 100 buttons with different IDs?
I can duplicate 100x function. However, this is not very elegant and good solution.
How to easily and effectively solve a problem for many buttons?
The function performed is the same for all buttons.

Add a class bind to this:
$(document).ready(function(){
//dot (.) selector binds to classes
$('.boundButton').click(function(){
//clicked button
var $this = $(this);
alert($this.attr('id'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" class="boundButton">1</button>
<button id="2" class="boundButton">2</button>
<button id="3" class="boundButton">3</button>

You need to use a class instead of ID. For example, your JS code could look like:
$('.button-class').click(function() { ... } );
and your HTML might look like
<button name='example' class='button-class' id='exampleID'>Button Text</button>

Here is the basic example:
$(document).ready(function () {
$(".btn").on("click", function(){ //attach click event to all buttons with class "btn"
console.log($(this).attr("id")); //$(this) refers to the button clicked
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1" class="btn">Button 1</button>
<button id="btn2" class="btn">Button 2</button>
<button id="btn3" class="btn">Button 3</button>

Related

Simulate click with javascript with no element ID

<button
type="button"
class="blue"
data-events="click:onAddNote"
data-events-target="cpoe-LabResultDetailView"
>
Add Note
</button>
I'm trying to simulate / prompt a click of this button when I press a shortcut key sequence. However, I haven't been successful with anything other than through the class "blue", which works but also activates something else. How do I target the "data-events" or "data-events-target"?
Is there a way to something similar to:
$("click:onAddNote").trigger("click");
You can use querySelector and select the button with its attributes
var button = document.querySelector('[data-events="click:onAddNote"]');
button.onclick = ()=>console.log('Clicked');
button.click()
<button
type="button"
class="blue"
data-events="click:onAddNote"
data-events-target="cpoe-LabResultDetailView"
>
Add Note
</button>
Why not just this?
const button = docuemnt.querySelector('button')
button.click()
There are many ways to select the <button> element.
Method-1
In the example below, the click event is fired by selecting the first <button> element with the .blue class style applied.
let button = document.getElementsByClassName('blue');
button[0].addEventListener('click', function() {
console.log("clicked");
});
<button type="button" class="blue">Add Note</button>
Method-2
The click event of the <button> element with the .blue class style applied using jQuery can be rendered as follows:
$(".blue").on('click', function(event) {
console.log("clicked");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="blue" data-events="click:onAddNote" data-events-target="cpoe-LabResultDetailView">Add Note</button>
Targeting the "data-events" attribute is simple, like this ...
$('button[data-events="click:onAddNote"]').on('click', function(){
console.log('clicked!');
});
<button
type="button"
class="blue"
data-events="click:onAddNote"
data-events-target="cpoe-LabResultDetailView"
>
Add Note
</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
See the jquery documentation for more information on running handlers -- Here

Jquery change status of button on click

I have 6 Buttons, I gave each button a Default Status of false, if the user clicks on a button that corresponding Status is switching to true. Now if I Switch a button all other button Statuses shall switch to false.
Something like this worked but what is a good way to Code this for many Buttons, I do not want to repeat myself that much:
toolOneStatus = false
$('#btn-tool-one').click(function() {
toolOneStatus = true;
toolTwoStatus = false; ....
}
You can use .data() for this. Check snippet below...
$('button').click(function(){
alert('status ' + $(this).data('status'));
if($(this).data('status')=="false"){
//do this
} else {
//do this
}
$(this).data('status','true')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" data-status="false">Button1</button>
<button type="button" data-status="false">Button2</button>
<button type="button" data-status="false">Button3</button>
<button type="button" data-status="false">Button4</button>
<button type="button" data-status="false">Button5</button>
<button type="button" data-status="false">Button6</button>
You can use a single click function and identify the button by a data-no attribute.
This sample adds a blue color to the active button while all others remain gray. The activeButton variable represents the number of the active button.
var activeButton = 0;
$('.mybtns').click(function() {
activeButton = $(this).data('no');
console.log('active='+activeButton);
$('.mybtns').css('background-color','rgb(221, 221, 221)');
$(this).css('background-color','lightblue');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="mybtns" data-no="1">Test1</button>
<button class="mybtns" data-no="2">Test2</button>
<button class="mybtns" data-no="3">Test3</button>
<button class="mybtns" data-no="4">Test4</button>
<button class="mybtns" data-no="5">Test5</button>
<button class="mybtns" data-no="6">Test6</button>
<button class="mybtns" data-no="7">Test7</button>
To loop through each of the buttons and execute some code for each, you can use the aptly named .each() function available in jquery. You can find the documentation for it here - each()
Whenever a button is clicked, .each() executes the function for all the elements with class=buttons and set the status=false. Inside the function you can use the $(this) selector to select the object of the current iteration. Finally outside the loop, the button which triggered the event, is given status=true.
$('button').click(function() {
$(".buttons").each(function(index) {
// Looping through each element having class "buttons"
$(this).data("status", "false"); //Setting every button to false.
$(this).next().html($(this).data("status"));
});
$(this).data("status", "true"); // Outside the loop, setting status true for the button which triggered the click event.
$(this).next().html($(this).data("status"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="buttons" id="button1" data-status="false">Button1</button><span id="p1"></span>
<button type="button" class="buttons" id="button2" data-status="false">Button2</button><span id="p2"></span>
<button type="button" class="buttons" id="button3" data-status="false">Button3</button><span id="p3"></span>
<button type="button" class="buttons" id="button4" data-status="false">Button4</button><span id="p4"></span>

On Button Click - Change Span Content - More efficient way?

I am looking for some assistance and there must be a better way to code this. I have a series of buttons that change the same span Id and well I can get it to work but it seems like an excessive number of actions. Is there a way to make this more efficient? Any help would be appreciated. Thank you!
jQuery("#All-Btn").click(function(event) {
event.preventDefault();
jQuery('#Type').html("red wine");
});
jQuery("#Awesome-Btn").click(function(event) {
event.preventDefault();
jQuery('#Type').html("Awesome");
});
You can use a custom function:
function myBtn(id, text) {
$(id).click(function (e) {
e.preventDefault();
$('#Type').html(text);
})
}
myBtn("#All-Btn", "red wine");
myBtn("#Awesome-Btn", "Awesome");
Well, provided you gave all your buttons a shared class and a data element you could reduce the logic as such.
<input type="button" id="All-Btn" class="typeButton" data-type="red wine">
<input type="button" id="Awesome-Btn" class="typeButton" data-type="some other value">
jQuery('.typeButton').on('click', function(e){
e.preventDefault();
jQuery('#Type').html(jQuery(this).data('type'));
}
Common Approach is using data attributes
$("[data-test]").on("click", function () {
var text = $(this).data("test");
$("#out").text(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button data-test="Red">Button 1</button>
<button data-test="Blue">Button 2</button>
<button data-test="Green">Button 3</button>
<div id="out"></div>
Another approach is a lookup
var text = {
btn1 : "Red",
btn2 : "Green",
btn3 : "Blue",
};
$(".btn").on("click", function () {
var id = $(this).attr("id");
$("#out").text(text[id]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btn1" class="btn">Button 1</button>
<button id="btn2" class="btn">Button 2</button>
<button id="btn3" class="btn">Button 3</button>
<div id="out"></div>
Or a switch
$(".btn").on("click", function () {
var id = $(this).attr("id"),
text;
switch (id) {
case "btn1" :
text = "Red";
break;
case "btn2" :
text = "Green";
break;
case "btn3" :
text = "Blue";
break;
}
$("#out").text(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btn1" class="btn">Button 1</button>
<button id="btn2" class="btn">Button 2</button>
<button id="btn3" class="btn">Button 3</button>
<div id="out"></div>
You could make object, with key-value pairs: Key is button id, value is span html, e.g:
buttons={
'All-Btn':'red wine',
'Awesome-Btn':'Awesome'
};
And then iterate through it:
$.each( buttons, function( key, value ) {
jQuery("#"+key).click(function(event) {
event.preventDefault();
jQuery('#Type').html(value);
});
});
buttons={
'All-Btn':'red wine',
'Awesome-Btn':'Awesome'
};
$.each( buttons, function( key, value ) {
jQuery("#"+key).click(function(event) {
event.preventDefault();
jQuery('#Type').html(value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="All-Btn">
fffff
</div>
<div id="Awesome-Btn">
fffffffffff
</div>
<span id="Type"></span>
However, you have to type... a lot, again. :)
You can store the text that you want to display as an attribute of the button (ex data-text). Then, you just need one function to handle the event
jQuery("#All-Btn, #Awesome-Btn").click(function(event) {
event.preventDefault();
var text = jQuery(this).data('text');
jQuery('#Type').html(text);
});
How about that?
The first way that came to mind was to use a data- attribute to specify the text associated with each button, and then bind a single, delegated click handler to handle clicks on all buttons with that attribute.
Notice that then your buttons don't need IDs.
$("body").on("click", "[data-text]", function() {
$("#type").text($(this).attr("data-text"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="type"> </span><br>
<button data-text="Awesome">Awesome</button>
<button data-text="Whatever">Something</button>
<button data-text="Greetings">Hello</button>
<button data-text="Fare well">Goodbye</button>
<button>This button does nothing because it has no data- attribute</button>
(I've bound the delegated click handler to the body, but the best practice is to bind it to the closest common parent of the elements in question.)

addEventListener with multiple elements [duplicate]

This question already has answers here:
AddEventListener for multiple elements doesn't work with "focus" event
(3 answers)
Closed 6 years ago.
I started working with javascript.
I have two buttons, and want change backgroundColor when click on any of these buttons.
But my code doesn't work.
This is my code:
document.getElementsByTagName("button").addEventListener("click", function(){
func(this)
});
function func(element){
element.style.backgroundColor="gray";
}
<div id="area">
<button type="button" class="btn" id="btn1">Play With Me!</button>
<button type="button" class="btn" id="btn2">Play With Me!</button>
</div>
is there any way that an addEventListener works with multiple elements?
The best way is to have as few event listeners as possible in your code. So instead of attaching an event listener to each and every button, you can attach 1 single event listener to the area div and make suitable changes based on event.target attribute.
Run the below working code snippet:
document.getElementById('area').addEventListener('click', function(event) {
func(event.target);
});
function func(element) {
element.style.backgroundColor = "blue";
}
<div id="area">
<button type="button" class="btn" id="btn1">Play With Me!</button>
<button type="button" class="btn" id="btn2">Play With Me!</button>
</div>
You could do it like this or DEMO
var button = document.getElementsByTagName("button");
for (var i = 0; i < button.length; i++) {
button[i].addEventListener("click", function() {
this.style.backgroundColor = "gray";
});
}
<div id="area">
<button type="button" class="btn" id="btn1">Play With Me!</button>
<button type="button" class="btn" id="btn2">Play With Me!</button>
</div>
Try this
<button type="button" onclick="myFunction()">Set background color</button>
<button type="button" onclick="myFunction()">Set background color</button>
<script>
function myFunction() {
document.body.style.backgroundColor = "red";
}
</script>

How to hide div after clicking on button?

I would like to hide the div (which is "hide-div") as soon as the user cliks on the button when there is a navigation to the same page. Please help me on this. Thanks
<div id="hide-div">
<button type="button" title="test" class="button btn-small" onclick="setLocation('abc.com');"><span>'Add to Cart'</span></button>
</div>
Using Vanilla JavaScript. Although I recommend using event handler instead of inline JS, this is in view of your code.
Hide the element using style.display
You can redirect the page after hiding the button using window.location
function setLocation(loc) {
document.getElementById('hide-div').style.display = 'none';
window.location = loc;
}
<div id="hide-div">
<button type="button" title="test" class="button btn-small" onclick="setLocation('http://google.com')"><span>'Add to Cart'</span></button>
</div>
You can do this by simple jquery
<script>
jQuery(document).ready(function($) {
$(".button").click(function(){
$("div").fadeOut();
});
});
</script>
Using jQuery you can do this in your onclick:
$('#hide-div').hide()
http://api.jquery.com/hide/
Use jQuery to hide it:
$('#hide-div button').click(function(){
$(this).parent().hide();
});
I assume you have jQuery added to your page already. So, something like this maybe:
$('#hide-div .button').on('click', function() {
$('#hide-div').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hide-div">
<button type="button" title="test" class="button btn-small" onclick="setLocation('abc.com');"><span>'Add to Cart'</span></button>
</div>

Categories

Resources