write multiple buttons in one function using javascript/jquery [duplicate] - javascript

This question already has answers here:
call the same jQuery function in multiple buttons
(10 answers)
Using multiple buttons on same function that redirects to different functions
(5 answers)
Using the same function with multiple buttons
(3 answers)
Closed 3 years ago.
I want to write multiple buttons in one function using javascript/jquery. My problem is that
Everytime im writing a separate function for each button with separate onclick event like in the below code snippet
I want to write one function that includes multiple buttons
function todaySales() {
alert('button1');
}
function yesterdaySales() {
alert('button2');
}
function wtdsales() {
alert('button3');
}
function llsales() {
alert('button4');
}
function lastSevenDays() {
alert('button5');
}
function lastThirtyDays() {
alert('button6');
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<button id="but1" class="btn btn-outline-info" onclick="todaySales();">Today</button>
<button id="but2" class="btn btn-outline-info" onclick="yesterdaySales();">Yesterday</button>
<button id="but3" class="btn btn-outline-info" onclick="wtdsales();">WTD</button>
<button id="but4" class="btn btn-outline-info" onclick="llsales();">MTD</button>
<button id="but5" class="btn btn-outline-info" onclick="lastSevenDays();">Last 7 Days</button>
<button id="but6" class="btn btn-outline-info" onclick="lastThirtyDays()">Last 30 Days</button>

You can give the same function name with different parameter value like
<button id="but1" class="btn btn-outline-info" onclick="salesAction(this, 'todaySales');">Today</button>
<button id="but2" class="btn btn-outline-info" onclick="salesAction(this, 'yesterdaySales');">Yesterday</button>
<button id="but3" class="btn btn-outline-info" onclick="salesAction(this, 'wtdsales');">WTD</button>
<button id="but4" class="btn btn-outline-info" onclick="salesAction(this, 'llsales');">MTD</button>
<button id="but5" class="btn btn-outline-info" onclick="salesAction(this, 'lastSevenDays');">Last 7 Days</button>
<button id="but6" class="btn btn-outline-info" onclick="salesAction(this, 'lastThirtyDays')">Last 30 Days</button>
<script>
function salesAction(thisObj, $salesVal){
console.log($salesVal);
// use switch to write separate logic for each sales
}
</script>
example : https://codepen.io/kaslab/pen/rROyVr

function clickButton(buttonName){
alert(buttonName);
}
just need seed a params to function. It's easy.

You can use the same click handler function and just strip data out of your button's properties or you can pass data as parameters to that function.
function clickHandler(ev) {
var target = event.target
console.log(target.id, target.textContent) // or whatever property
}
<button id="but1" class="btn btn-outline-info" onclick="clickHandler();">Today</button>
<button id="but2" class="btn btn-outline-info" onclick="clickHandler();">Yesterday</button>
<button id="but3" class="btn btn-outline-info" onclick="clickHandler();">WTD</button>
<button id="but4" class="btn btn-outline-info" onclick="clickHandler();">MTD</button>
<button id="but5" class="btn btn-outline-info" onclick="clickHandler();">Last 7 Days</button>
<button id="but6" class="btn btn-outline-info" onclick="clickHandler();">Last 30 Days</button>

Try it
$(document).ready(function(){
$(".btn").on('click',function() {
alert( $(this).text())
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<button id="but1" class="btn btn-outline-info">Today</button>
<button id="but2" class="btn btn-outline-info">Yesterday</button>
<button id="but3" class="btn btn-outline-info">WTD</button>
<button id="but4" class="btn btn-outline-info">MTD</button>
<button id="but5" class="btn btn-outline-info">Last 7 Days</button>
<button id="but6" class="btn btn-outline-info">Last 30</button>

using jQuery is very simple: suppose your buttons are direct children of a div element having id=“buttonsArray”
$(‘#buttonsArray’).on(‘click’, ‘button’, function() {
alert($(this));
});
As you can see, this overload of the .on() method let you dynamically bind to the clicked element. You can use data attribute within every button to create a switch statement inside that function and then differentiate behavior of your function depending on what button was pressed
<button data-value=“oneValue”>
<button data-value=“otherValue”>
The switch statement:
var myValue = $(this).data()[“value”]
switch (myValue) {
case “oneValue”:
// do something
break;
case “otherValue”:
// do something else
break;
}

HTML
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<button id="but1" class="btn btn-outline-info" onclick="onefunction();">Today</button>
<button id="but2" class="btn btn-outline-info" onclick="onefunction();">Yesterday</button>
<button id="but3" class="btn btn-outline-info" onclick="onefunction();">WTD</button>
<button id="but4" class="btn btn-outline-info" onclick="onefunction();">MTD</button>
<button id="but5" class="btn btn-outline-info" onclick="onefunction();">Last 7 Days</button>
<button id="but6" class="btn btn-outline-info" onclick="onefunction()">Last 30 Days</button>
JS
function onefunction() {
if($(this).attr("id") == "but1"){
alert('button1');
}
else if($(this).attr("id") == "but2"){
alert('button2');
}
...
}

Related

JavaScript Calculator equal button returns "undefined"

I'm working on a simple JavaScript calculator. Everything seems fine and other buttons works as expected except for the equal button which returns an "undefined" when it is clicked. On clicking the equal button, "if" the value of the screen is empty, I want the value of the screen to be set to an empty string, else, the new screen.value should be the result of an eval();
I've gone over the code several times and can't find what the problem is. Pls help. Thanks.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="calculator.css">
</head>
<body>
<div class="wrapper">
<form>
<input type="text" class="screen" placeholder="0" value="";>
</form>
<div class="buttons">
<button type="button" class="btn btn-yellow" data-num="*">*</button>
<button type="button" class="btn btn-yellow" data-num="/">/</button>
<button type="button" class="btn btn-yellow" data-num="-">-</button>
<button type="button" class="btn btn-yellow" data-num="+">+</button>
<button type="button" class="btn btn-grey" data-num="9">9</button>
<button type="button" class="btn btn-grey" data-num="8">8</button>
<button type="button" class="btn btn-grey" data-num="7">7</button>
<button type="button" class="btn btn-grey" data-num="6">6</button>
<button type="button" class="btn btn-grey" data-num="5">5</button>
<button type="button" class="btn btn-grey" data-num="4">4</button>
<button type="button" class="btn btn-grey" data-num="3">3</button>
<button type="button" class="btn btn-grey" data-num="2">2</button>
<button type="button" class="btn btn-grey" data-num="1">1</button>
<button type="button" class="btn btn-grey" data-num="0">0</button>
<button type="button" class="btn btn-grey" data-num=".">.</button>
<button type="button" class="btn btn-equal">=</button>
<button type="button" class="btn btn-clear">C</button>
</div>
</div>
<script type="text/javascript" src="calculator.js"></script>
</body>
</html>
JAVASCRIPT CODE HERE
(function(){
let screen = document.querySelector(".screen");
let buttons = document.querySelectorAll(".btn");
let equal = document.querySelector(".btn-equal");
let clear = document.querySelector(".btn-clear");
buttons.forEach(function(button) {
button.addEventListener("click", function(e){
let value = e.target.dataset.num;
screen.value += value;
})
});
equal.addEventListener("click", function(e){
if (screen.value === "") {
screen.value = "";
} else{
let answer = eval(screen.value);
screen.value = answer;
}
})
clear.addEventListener("click", function(){
screen.value = "";
})
})();
The issue because you give the "=" button a ".btn" class, which has the 'click' event listener, and because the "=" button doesn't have attribute data-num, the input will be concatenate with undefined, so any calculation you will do will be end with "undefined" which give Syntax error.
So just removing "btn" class from "=" button will solve the issue.
This works, please check.
(function(){
let screen = document.querySelector(".screen");
let buttons = document.querySelectorAll(".btn");
let equal = document.querySelector(".btn-equal");
let clear = document.querySelector(".btn-clear");
buttons.forEach(function(button) {
button.addEventListener("click", function(e){
let value = e.target.dataset.num;
console.log(value)
screen.value += value;
})
});
equal.addEventListener("click", function(e){
if (screen.value === "") {
screen.value = "";
} else{
console.log(screen.value)
let answer = eval(screen.value);
screen.value = answer;
}
})
clear.addEventListener("click", function(){
screen.value = "";
})
})();
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="calculator.css">
</head>
<body>
<div class="wrapper">
<form>
<input type="text" class="screen" placeholder="0" value="";>
</form>
<div class="buttons">
<button type="button" class="btn btn-yellow" data-num="*">*</button>
<button type="button" class="btn btn-yellow" data-num="/">/</button>
<button type="button" class="btn btn-yellow" data-num="-">-</button>
<button type="button" class="btn btn-yellow" data-num="+">+</button>
<button type="button" class="btn btn-grey" data-num="9">9</button>
<button type="button" class="btn btn-grey" data-num="8">8</button>
<button type="button" class="btn btn-grey" data-num="7">7</button>
<button type="button" class="btn btn-grey" data-num="6">6</button>
<button type="button" class="btn btn-grey" data-num="5">5</button>
<button type="button" class="btn btn-grey" data-num="4">4</button>
<button type="button" class="btn btn-grey" data-num="3">3</button>
<button type="button" class="btn btn-grey" data-num="2">2</button>
<button type="button" class="btn btn-grey" data-num="1">1</button>
<button type="button" class="btn btn-grey" data-num="0">0</button>
<button type="button" class="btn btn-grey" data-num=".">.</button>
<button type="button" class="btn-equal">=</button>
<button type="button" class="btn btn-clear">C</button>
</div>
</div>
</body>
</html>

How to html if statement

I want to display a button only if a statement is true:
<button type="button" id="btn1" class ="btn1"> btn1 </button>
<button type="button" id="btn2" class="btn2"> btn2 </button>
<script>
var statement= 1;
if (statement== 1){
<button type="button" id="btn3" class="btn3"> btn3</button>
}
</script>
My html looks like this atm. But It doesnt work, even if my statement is 1=1. How can I achieve this working without a button click event or some interaction?
You could use document.write to directly write into the HTML output. (Mentioned by #Ivar in the comments) Just place the script where you want to write something.
<button type="button" id="btn1" class="btn1"> btn1 </button>
<button type="button" id="btn2" class="btn2"> btn2 </button>
<script>
var statement = 1;
if (statement == 1) {
document.write('<button type="button" id="btn3" class="btn3"> btn3</button>');
}
</script>
You can decide where to display the button by moving the script tag to the location where you want to insert it. See example.
However a more commonly used approach is to manipulate the DOM instead of "echoing" your result in JavaScript.
You could have a button and change it's display state:
var statement = 1;
if (statement == 1) {
document.querySelector("#btn3").style.display = "inline-block"
}
<button type="button" id="btn1" class="btn1"> btn1 </button>
<button type="button" id="btn2" class="btn2"> btn2 </button>
<button type="button" id="btn3" class="btn3" style="display: none;"> btn3</button>
You could create a button and add it to the DOM:
const button = document.createElement("button")
button.type = "button"
button.id = "btn3"
button.classList.add("btn3") // Adds one class with the name btn3
button.textContent = "btn3" // Writes what is inside <button>....</button>
document.body.append(button) // Adds element below each other elements
<button type="button" id="btn1" class="btn1"> btn1 </button>
<button type="button" id="btn2" class="btn2"> btn2 </button>
<button type="button" id="btn3" class="btn3" style="display: none;"> btn3</button>
More about:
https://www.w3schools.com/js/js_htmldom_methods.asp
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents (Source: #Teemu)
https://www.youtube.com/watch?v=y17RuWkWdn8
<button type="button" id="btn1" class ="btn1"> btn1 </button>
<button type="button" id="btn2" class="btn2"> btn2 </button>
<script>
var statement= 1;
if (statement == 1){
var x = document.createElement("button");
var t = document.createTextNode("Click me");
x.appendChild(t);
document.body.appendChild(x)
}
</script>

how to enable/disable buttons in HTML jscript

I am trying to enable buttons on a web page using a js funtion for a django project.
I am new this so please be cool :-)
function change(id) {
var elem = document.getElementById(id);
let editID = "edit_".concat(id);
let deleteID = "delete_".concat(id);
if (elem.value == "Undo") {
elem.value = "Modify";
editButtonElement = document.getElementsByName(editID);
editButtonElement.disabled = false;
deleteButtonElement = document.getElementsByName(deleteID);
deleteButtonElement.disabled = false;
} else {
elem.value = "Undo";
editButtonElement = document.getElementsByName(editID);
editButtonElement.disabled = true;
deleteButtonElement = document.getElementsByName(deleteID);
deleteButtonElement.disabled = true;
}
}
<input onclick="change(id)" type="button" value="Modify" id="11" class="btn btn-info"></input>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary" disabled="false" id="edit_11">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false" id="delete_11">Delete</button>
</div>
<br>
<input onclick="change(id)" type="button" value="Modify" id="22" class="btn btn-info"></input>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary" disabled="false" id="edit_22">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false" id="delete_22">Delete</button>
</div>
<br>
What I would like to happen is for the name of the main button change from "Modify" to "Undo", which happens. But I'd also like for the two related Edit and Delete buttons to be enabled so as to press them.
Anyone can tell me what I am doing wrong?
Thanks!
You could assign an external event listener to process the buttons clicks using an array of possible states so that a simple toggle mechanism is created.
FYI: input elements are self-closing so you do not supply a </input> as with the majority of HTML tags.
To concatenate in Javascript you use + rather than . which is the default in PHP so you should change "edit_".concat(id) to "edit_" + id
const states=['Undo','Modify'];
document.querySelectorAll('input[type="button"]').forEach( bttn=>{
bttn.addEventListener('click', function(e){
this.value=states[ 1 - states.indexOf( this.value ) ];
let div=document.querySelector('div.btn-group[data-id="'+this.id+'"]');
div.querySelectorAll('button').forEach(bttn=>{
bttn.disabled = this.value==states[1];
});
});
})
<input type="button" value="Modify" id="11" class="btn btn-info" />
<div class="btn-group" role="group" aria-label="Basic example" data-id=11>
<button type="button" class="btn btn-secondary" disabled="false">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false">Delete</button>
</div>
<br /><br />
<input type="button" value="Modify" id="22" class="btn btn-info" />
<div class="btn-group" role="group" aria-label="Basic example" data-id=22>
<button type="button" class="btn btn-secondary" disabled="false">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false">Delete</button>
</div>
<br /><br />
You should use getElementById instead of getElementsByName
function change(id) {
var elem = document.getElementById(id);
let editID = "edit_".concat(id)
let deleteID = "delete_".concat(id)
if (elem.value == "Undo") {
elem.value = "Modify";
editButtonElement = document.getElementById(editID)
editButtonElement.disabled = false
deleteButtonElement = document.getElementById(deleteID)
deleteButtonElement.disabled = false
} else {
elem.value = "Undo";
editButtonElement = document.getElementById(editID)
editButtonElement.disabled = true
deleteButtonElement = document.getElementById(deleteID)
deleteButtonElement.disabled = true
}
}
<input onclick="change(id)" type="button" value="Modify" id="11" class="btn btn-info"></input>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary" disabled="false" id="edit_11">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false" id="delete_11">Delete</button>
</div>
<br></br>
<input onclick="change(id)" type="button" value="Modify" id="22" class="btn btn-info"></input>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary" disabled="false" id="edit_22">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false" id="delete_22">Delete</button>
</div>
To avoid repeating yourself, you could toggle all buttons in one function. Also you could use a switch statement if you want to handle more than "Modify" and "Undo", for instance :
function toggleButtons(id, disabled) {
["edit", "delete"].forEach(action => window[`${action}_${id}`].disabled = disabled)
}
function change(id) {
const elem = window[id],
v = elem.value;
switch (v) {
case "Undo":
toggleButtons(id, true);
elem.value = "Modify";
break;
default:
toggleButtons(id, false);
elem.value = "Undo";
break;
}
}
<input onclick="change(id)" type="button" value="Modify" id="11" class="btn btn-info"></input>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary" disabled="false" id="edit_11">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false" id="delete_11">Delete</button>
</div>
<br><br>
<input onclick="change(id)" type="button" value="Modify" id="22" class="btn btn-info"></input>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary" disabled="false" id="edit_22">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false" id="delete_22">Delete</button>
</div>
I'm pretty sure this is going to work.
function change(id) {
var elem = document.getElementById(id);
console.log(elem);
let editID = "edit_".concat(id);
let deleteID = "delete_".concat(id);
if (elem.value == "Undo") {
elem.value = "Modify";
let editButtonElement = document.getElementById(editID);
editButtonElement.disabled = false;
let deleteButtonElement = document.getElementById(deleteID);
deleteButtonElement.disabled = false;
} else {
elem.value = "Undo";
let editButtonElement = document.getElementById(editID);
editButtonElement.disabled = true;
let deleteButtonElement = document.getElementById(deleteID);
deleteButtonElement.disabled = true;
}
}
<input onclick="change('eleven')" type="button" value="Modify" id="eleven" class="btn btn-info"></input>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary" disabled="false" id="edit_eleven">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false" id="delete_eleven">Delete</button>
</div>
<br></br>
<input onclick="change('twentyTwo')" type="button" value="Modify" id="twentyTwo" class="btn btn-info"></input>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary" disabled="false" id="edit_twentyTwo">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false" id="delete_twentyTwo">Delete</button>
</div>
you forgot to declare the variables using a keyword like "let" or "var" and used getElementsByName instead of getElementById. It is also a good practice to avoid using numbers as id and to use semicolons. Your code is very clean though

How to completely change the contents of a div onclick?

I'm only starting to delve into javascript and have no real knowledge of how to work with jQuery, but I'm working on a page which features a control panel. I'm trying to get the functions of the control panel to change on clicking a button on it.
Here's what I have so far;
html:
<div id="functions">
<button id="prob" onclick="myproblem()" type="button" title="prob"></button>
<button id="button1" onclick="works1()" type="button" title="button1"></button>
<button id="button2" onclick="works2" type="button" title="button2"></button>
</div>
Javascript:
function myproblem() {
document.getElementById("functions").html('
<button id="prob" onclick="myproblem()" type="button" title="prob"></button>
<button id="button3" onclick="works3()" type="button" title="button3"></button>
<button id="button4" onclick="works4()" type="button" title="button4"></button>');
}
The button I want to use to change the html is contained within the div which is getting changed. There are other onclick functions in that div which were working fine until I wrote the myproblem() code into my js file. With that section of code there, none of my js works.
This is a localhosted page, it won't be online.
I'm assuming I need to use jQuery to pull this off, but I have no idea how.
Thanks,
Use the innerHTML() method in JavaScript:
function myproblem() {
document.getElementById("functions").innerHTML ='<button id="prob" onclick="myproblem()" type="button" title="prob"></button> <button id="button3" onclick="works3()" type="button" title="button3"></button> <button id="button4" onclick="works4()" type="button" title="button4"></button>'
}
In Jquery you can use the html method
$(".functions").html('Your html code goes here')
<div class="temp01" style="display:none">
<button id="prob" onclick="myproblem('temp02')" type="button" title="prob"></button>
<button id="button1" onclick="works1()" type="button" title="button1"></button>
<button id="button2" onclick="works2" type="button" title="button2"></button>
</div>
<div class="temp02" style="display:none">
<button id="prob" onclick="myproblem('temp01')" type="button" title="prob"></button>
<button id="button3" onclick="works3()" type="button" title="button3"></button>
<button id="button4" onclick="works4()" type="button" title="button4"></button>
</div>
<div class="functions">
<button id="prob" onclick="myproblem('temp02')" type="button" title="prob"></button>
<button id="button1" onclick="works1()" type="button" title="button1"></button>
<button id="button2" onclick="works2" type="button" title="button2"></button>
</div>
<script>
function myproblem(x){ //x could be "temp01" or "temp02"
$(".functions").html("");
$("." + x).clone().attr("id","functions").show().appendTo(".functions");
}
</script>

click button => prevent onclick & show modal, click yes => callback the onclick function

I have a page with multiple input That All look like the below.
And I want to display a modal before executing the onclick.
The onclick function should be running when the yes button of the modal is clicked.
My problem is that when I click yes, the function executed is always that of the first input. Then I have to execute the function of the clicked button
Many thanks for any help with this.
HTML:
<input id="first" class="btn btn-success" type="button" onclick="doFirstFunction()" value="FirstFunction"/><br>
<input id="second" class="btn btn-success" type="button" onclick="doSecondFunction()" value="SecondFunction"/><br>
<input id="third" class="btn btn-success" type="button" onclick="doThirdFunction()" value="ThirdFunction"/>
//Modal
<div class="modal fade in" id="confirmationYesNo" aria-hidden="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Confirmation</h4>
</div>
<div class="modal-body">
Are you sure ?
<button id="btnYes" type="button" class="btn btn-danger" >Yes</button>
<button type="button" class="btn btn-success" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
JS:
var input = $("input[type=button]");
var defaultFunctionToCallLater = $("input").prop('onclick');
console.log("defaultFunctionToCallLater", defaultFunctionToCallLater);
$("input").prop("onclick", null );
//$("input").removeProp("onclick");
input.click(function(e){
var $target = $(e.target);
var isThird = (e.target.id == 'third');
if(!(isThird)){
$('#confirmationYesNo').appendTo("body").modal({
backdrop:'static',keyboard:false}).show();
$("#btnYes").click(function(){
addEventListener('click', defaultFunctionToCallLater);
});
}
});
function doFirstFunction(){
location.href="link1";
};
function doSecondFunction(){
location.href="link2";
};
function doThirdFunction(){
location.href="link3";
};
<input id="first" class="btn btn-success" type="button" onclick="modalFunction(1)" value="FirstFunction"/><br>
<input id="second" class="btn btn-success" type="button" onclick="modalFunction(2)" value="SecondFunction"/><br>
<input id="third" class="btn btn-success" type="button" onclick="modalFunction(3)" value="ThirdFunction"/>
And here is the JS
function openModal(callbackFunc) {
switch(callbackFunc) {
case 1:
$("#btnYes").on('click', doFirstFunction);
break;
case 2:
$("#btnYes").on('click', doSecondFunction);
break;
case 3:
$("#btnYes").on('click', doThirdFunction);
break;
}
}
All youre inputs should call showModal(id) (id = 1; id=2; ...)
The modal function will just show the modal and redirect to your js functions when you press YES
function showModal(id){
(showtheModal)
IF YES IS PRESSED
switch(id){
case 1:
doFirstFunction();
break;
case 3:
doSecondFunction();
break;
case 3:
doThirdFunction();
break;
}
}

Categories