Jquery change status of button on click - javascript

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>

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

how can i make buttons with numbers from 0-9 that adds into a textbox when i press them

I want to make a "numeric keyboard" that shows buttons with symbols from 0-9. When I press each button it is suppose to add up.
So lets say i press 3 , 4 then 1 it should say 341 on the text box or number box idk (srry im new).
I have only taken some examples from my teacher so i dont know if this is the right method.
I tried this on button 0:
<button onclick="showZero()">0</button>
<button onclick="">1</button>
<button onclick="">2</button>
<button onclick="">3</button>
<button onclick="">4</button>
<button onclick="">5</button>
<button onclick="">6</button>
<button onclick="">7</button>
<button onclick="">8</button>
<button onclick="">9</button>
<br>
<input type="text" id="txtZero">
window.onload = start;
function start() {}
function showZero()
{
var zero = document.getElementById("Number");
zero.Value="0";
document.querySelector("txtZero").appendChild(zero);
}
Am i using wrong method? I saw my teacher example, but he was using this to generate more buttons and not numbers like im trying to do.
EDIT: I edited my answer to provide a better answer that doesn't use inline event handling. I also wrapped the code into DOMContentLoaded event listener to make sure JS runs after the DOM is fully loaded.
function ready() {
// The textfield element
textField = document.getElementById("field")
// The reset button
resetButton = document.getElementById("resetbtn")
// Get all the buttons to an Array
buttons = document.getElementsByClassName("btn")
// Add click event listener to all button elements and insert their inner text as value to the text field
Array.prototype.forEach.call (buttons, (button) => {
button.addEventListener("click", () => {
textField.value += button.innerText
})
})
// Add click event listener to reset button
resetButton.addEventListener("click", () => {
textField.value = null
})
}
document.addEventListener("DOMContentLoaded", ready);
input, button {
padding: 3px 6px;
margin: 3px;
}
<button class="btn">0</button>
<button class="btn">1</button>
<button class="btn">2</button>
<button class="btn">3</button>
<button class="btn">4</button>
<button class="btn">5</button>
<button class="btn">6</button>
<button class="btn">7</button>
<button class="btn">8</button>
<button class="btn">9</button>
<br>
<input type="text" id="field"><button id="resetbtn">Reset</button>
Follow the code to it:
Add function setNumber to set number in field text.
Change function showZero to resetNumber if contains the value in field text insert zero.
function resetNumber()
{
document.getElementById("field").value = '0';
}
function setNumber(number) {
document.getElementById("field").value = document.getElementById("field").value === '0' ? '' : document.getElementById("field").value += number;
}
<html>
<body>
<button onclick="resetNumber()">Reset</button>
<button onclick="setNumber(0)">0</button>
<button onclick="setNumber(1)">1</button>
<button onclick="setNumber(2)">2</button>
<button onclick="setNumber(3)">3</button>
<button onclick="setNumber(4)">4</button>
<button onclick="setNumber(5)">5</button>
<button onclick="setNumber(6)">6</button>
<button onclick="setNumber(7)">7</button>
<button onclick="setNumber(8)">8</button>
<button onclick="setNumber(9)">9</button>
<br />
<input type="text" id="field" />
</body>
</html>

One function - many buttons

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>

JQuery Detect Which File Upload Button Clicked [duplicate]

How to detect which dynamic button is clicked?
Note: The #dCalc Element is added dynamically...
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<input id="firstNumber" type="text" maxlength="3" />
<input id="secondNumber" type="text" maxlength="3" />
<input id="btn1" type="button" value="Add" />
<input id="btn2" type="button" value="Subtract" />
<input id="btn3" type="button" value="Multiply" />
<input id="btn4" type="button" value="Divide" />
</div>
</div>
$("input").click(function(e){
var idClicked = e.target.id;
});
$(function() {
$('input[type="button"]').click(function() { alert('You clicked button with ID:' + this.id); });
});
Since the block is added dynamically you could try:
jQuery( document).delegate( "#dCalc input[type='button']", "click",
function(e){
var inputId = this.id;
console.log( inputId );
}
);
demo http://jsfiddle.net/yDNWc/
jQuery can be bound to an individual input/button, or to all of the buttons in your form. Once a button is clicked, it will return the object of that button clicked. From there you can check attributes such as value...
$('#dCalc input[type="button"]').click(function(e) {
// 'this' Returns the button clicked:
// <input id="btn1" type="button" value="Add">
// You can bling this to get the jQuery object of the button clicked
// e.g.: $(this).attr('id'); to get the ID: #btn1
console.log(this);
// Returns the click event object of the button clicked.
console.log(e);
});
Detect event on dynamically created elements
Two examples, jQuery and vanilla JavaScript ahead:
jQuery
Use the .on() method with delegated events, which follows this syntax:
$("staticParentSelector").on("eventName", "dynamicChildSelector", handlerFn);
Example:
// Assign event listeners to dynamic child elements
// Will work for either existent elements or inserted in the future
$("#dBlock").on("click", '[type="button"]', (evt) => {
const staticParent = evt.delegateTarget; // This is #dBlock
const dynamicChild = evt.currentTarget; // This is the dynamic child
console.log(`Static Parent ID is: ${staticParent.id}`)
console.log(`Dynamic child ID is: ${dynamicChild.id}`)
});
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<button type="button" id="btn1">Add</button>
<button type="button" id="btn2">Subtract</button>
<button type="button" id="btn3">Multiply</button>
<button type="button" id="btn4">Divide</button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
JavaScript
The same in vanilla JavaScript can be achieved like the following, with the difference in that JS has no notion of delegateTarget (which is a jQuery property on their proprietary Event object) therefore the slight modification:
// Assign event listeners to dynamic child elements
// Will work for either existent elements or inserted in the future
document.querySelector("#dBlock").addEventListener("click", (evt) => {
const staticParent = evt.currentTarget; // This is #dBlock
const dynamicChild = evt.target.closest('[type="button"]'); // This is the dynamic child
if (!dynamicChild) return; // Do nothing (no designated dynamic child is clicked)
console.log(`Static Parent ID is: ${staticParent.id}`)
console.log(`Dynamic child ID is: ${dynamicChild.id}`)
});
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<button type="button" id="btn1">Add</button>
<button type="button" id="btn2">Subtract</button>
<button type="button" id="btn3">Multiply</button>
<button type="button" id="btn4">Divide</button>
</div>
</div>
as you can see neither of the above implementations stick solely on the Event.target Element per-se, for the reason that if we had i.e. an icon inside the buttons (like: <button id="add" type="button">Add <i class="icon-plus"></i></button>) and if a click landed on the icon directly, the Event.target would end up being the icon, not the Button Element - and we might miss to retrieve the needed data, like the specific button ID etc, resulting in a broken app logic.

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.)

Categories

Resources