How can i call a different functions seperately using a single button - javascript

I have to create a calculator but i have to use separate functions for add , subtract , division and multiply
there should be an equal to (=) button which upon clicking should display the result
operators should be selected using the dropdown box
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>calculator</title>
</head>
<body>
<h1 align="center">calculator</h1>
<script type="text/javascript">
function add()
{
var a=parseInt(document.getElementById("firstnumber").value);
var b=parseInt(document.getElementById("secondnumber").value);
var c=a+b
document.getElementById("answer").innerHTML=c;
}
function sub()
{
var a=parseInt(document.getElementById("firstnumber").value);
var b=parseInt(document.getElementById("secondnumber").value);
var c=a-b;
document.getElementById("answer").innerHTML=c;
}
function mul()
{
var a=parseInt(document.getElementById("firstnumber").value);
var b=parseInt(document.getElementById("secondnumber").value);
var c=a*b;
document.getElementById("answer").innerHTML=c;
}
function div()
{
var a=parseInt(document.getElementById("firstnumber").value);
var b=parseInt(document.getElementById("secondnumber").value);
var c=a/b;
document.getElementById("answer").innerHTML=c;
}
</script>
<p>First Number: <input id="firstnumber"></p>
<p>Second Number: <input id="secondnumber"></p>
<select id="operators">
<option value="add" onclick="add()">+</option>
<option value="sub" onclick="sub()">-</option>
<option value="mul" onclick="mul()">*</option>
<option value="div" onclick="div()">/</option>
</select>
<button onclick="add.call(this);sub.call(this);mul.call(this);div.call(this);">=</button>
<p id="answer"></p>
</body>
</html>

i think thats what you were looking for.
make sure to read what i wrote under the code
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>calculator</title>
</head>
<body>
<h1 align="center">calculator</h1>
<p>First Number: <input id="firstnumber" /></p>
<p>Second Number: <input id="secondnumber" /></p>
<select id="operators">
<option value="add">+</option>
<option value="sub">-</option>
<option value="mul">*</option>
<option value="div">/</option>
</select>
<button id="calcBtn">=</button>
<p id="answer"></p>
<script src="script.js"></script>
</body>
</html>
script.js:
document.getElementById("calcBtn").addEventListener("click", () => {
let operator = document.getElementById("operators").value;
let a = parseInt(document.getElementById("firstnumber").value);
let b = parseInt(document.getElementById("secondnumber").value);
switch (operator) {
case "add":
add();
break;
case "sub":
sub();
break;
case "mul":
mul();
break;
case "div":
div();
break;
default:
break;
}
function add() {
let c = a + b;
document.getElementById("answer").innerHTML = c;
}
function sub() {
let c = a - b;
document.getElementById("answer").innerHTML = c;
}
function mul() {
let c = a * b;
document.getElementById("answer").innerHTML = c;
}
function div() {
let c = a / b;
document.getElementById("answer").innerHTML = c;
}
});
dont use onclick, give element an id and then add event listenner to it works the same but addeventlistenner is better you can replace .addEventListener("click", () => { with .addEventListener("click", function() {
its up to you
always place your script tag directly above the body tag
use script src instead of script > code, it makes the html more clean
use let instead of var
switch case its like if, but in situations like that better, because its easier to write what to do depending on the value
usage:
switch(variable){
case "variable value":
code
break;
}
i think thats all

Related

if else loop not executing it's false condition? [duplicate]

This question already has answers here:
Javascript's .includes function not working correctly with array of objects [duplicate]
(2 answers)
How to determine if Javascript array contains an object with an attribute that equals a given value?
(27 answers)
Closed 4 months ago.
I'm trying to make an online library arrary that gets inputs for the value of a "book" object from a user form.
The problem is I made an if function to check if the currently submitted inputs match an already existing "book" object. Yet the function passes every input I make no matter if it's exactly the same.
Here is the Js
const submit = document.getElementById("submit");
const cardbox = document.getElementById("cardBox");
class Library {
constructor() {
this.books = [];
}
}
const myLibrary = new Library();
class Book {
constructor(title, author, pageCount, haveRead) {
this.title = title;
this.author = author;
this.pageCount = pageCount;
this.haveRead = haveRead;
}
}
function getBook() {
const book = new Book();
book.title = document.getElementById('title').value
book.author = document.getElementById('author').value
book.pageCount = document.getElementById('pageCount').value
book.haveRead = document.getElementById('haveRead').checked
function addBook() {
if (!myLibrary.books.includes(book)) {
myLibrary.books.push(book);
return makeCard(book);
}
else {
alert("Error: This book is already in library, pls reload and try again");
stop();
}
}
function makeCard() {
const card = document.createElement("div");
const titleCard = document.createElement("p");
const authorCard = document.createElement("p");
const pageCountCard = document.createElement("p");
titleCard.textContent = "Title: " + book.title;
authorCard.textContent = "Author: " + book.author;
pageCountCard.textContent = "Page Count: " + book.pageCount;
card.style.backgroundColor = "red";
card.style.fontSize = "20px"
cardbox.style.display = "flex"
card.appendChild(titleCard);
card.appendChild(authorCard);
card.appendChild(pageCountCard);
cardbox.appendChild(card);
return card;
}
addBook(book);
return book;
}
submit.addEventListener("click", function() {
getBook();
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="entry">
<form action="#" method="post">
<label for="title">Book title:</label>
<input type="text" id="title" name="book title" placeholder="insert book title here"><br>
<label for="author">Author:</label>
<input type="text" id="author" name="book author" placeholder="insert book author here"><br>
<label for="pageCount">How many pages is it?</label>
<input type="text" id="pageCount" name="pageCount" placeholder="insert page count here"><br>
<label for="read">Have you read already?</label>
<input type="checkbox" id="haveRead" name="read" placeholder="insert read status here">
</form>
<button type="submit" id="submit">Submit</button>
<div id="cardBox"></div>
</div>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
And there is the HTML for good measure. What am I missing here?

Match string case sensitive value with array

Here is my code!!!
I have one input field And
One of the array
I'm matching Input field entered value with arrray's list.
Prob : Unable to match capital value with array's list.
e.g if user enter one10 value so this one should be match or if user enter ONE10 in capital letter then this value should be match too.
function myFunctiontwo(){
var good = [
"one10",
"two10",
"three10"
];
var a = document.getElementById("code").value.split(' ');
var foundPresent = a.some(elem => good.indexOf(elem) > -1);
if(foundPresent === true){
alert("correct");
}else {
alert("wrong");
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input name="code" id="code" placeholder="code" required>
<button id="submit" id="sumbit" onclick="myFunctiontwo()">GO</button>
</body>
</html>
You can use the toLowerCase() method here. Assuming all your elements in good are lowercase you can just do elem.toLowerCase()
var foundPresent = a.some(elem => good.indexOf(elem.toLowerCase()) > -1);
When not you also should convert the array elements toLowerCase()
good = good.map(x => x.toLowerCase());
In the snippet below I added the element "FOur20" to the array.
As you can see four20 will give you the message correct
function myFunctiontwo(){
var good = [
"one10",
"two10",
"three10",
"FOur20"
];
good = good.map(x => x.toLowerCase());
console.log(good);
var a = document.getElementById("code").value.split(' ');
var foundPresent = a.some(elem => good.indexOf(elem.toLowerCase()) > -1);
if(foundPresent === true){
alert("correct");
}else {
alert("wrong");
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input name="code" id="code" placeholder="code" required>
<button id="submit" id="sumbit" onclick="myFunctiontwo()">GO</button>
</body>
</html>
Let's first make sure the good array is all lowercase:
good = good.map(word => word.toLowerCase());
Then, you can always convert to lowercase and check if it exists in the good array
var foundPresent = a.some(elem => good.contains(elem.toLowerCase()));
if(foundPresent === true) {
alert("correct");
}
else {
alert("wrong");
}

How to get latest inputs by pressing the up arrow (Javascript)

How can i get the latest inputs I entered in order. For example:
I declared an array with 20 elements and when I input something I delete the first element of the array and add at the end the input I just entered.
So when I press the upArrow button the last element of the array will appear as the new input. If I press one more time the upArrow I want my input to change to my second last element and so on.
It doesn't work in my jsfiddle link. It outputs another element from the array.
var singleValues;
var theInputsNumber = 19;
var latestInputs = new Array(20);
latestInputs.fill("Latest");
function clickMe(){
singleValues = $( "#input" ).val();
var c = latestInputs.shift();
latestInputs.push(singleValues);
$( "#output" ).append( singleValues);
$("#input").prop('value', '');
}
$(document).on('keypress',function(e) {
$('#input').bind('keydown', function(e) {
if (e.which === 38) {
$("#input").prop('value', latestInputs[theInputsNumber]);
theInputsNumber--;
}
});
if(e.which == 13) {
theInputsNumber=19;
clickMe();
}
});
<!DOCTYPE html>
<html>
<head>
<title>Think Fast Trivia</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="jqueryScript.js"></script>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="output" class="item1"></div>
<input autofocus type="text" name="input" id="input" />
<button id="send" onclick="clickMe()">Send</button>
</body>
</html>
You've missed the idea that you must determine (logic test) the value of the counter (theInputsNumber) in order to reset at the top (and the bottom) of the stack.
I renamed theInputsNumber counter and provided the UP key and DOWN key feature. I also did not limit the array size to 20 as that won't make a difference anyway (array size is not restricted in size as it is in other languages).
EDIT (based on comment): I've placed everything within the HTML so you can save this content into an HTML file and open with your browser. It will work just fine with no server.
<!DOCTYPE html>
<html>
<head>
<title>Think Fast Trivia</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="output" class="item1"></div>
<input autofocus type="text" name="input" id="input" />
<button id="send" onclick="clickMe()">Send</button>
<script>
var counter = 0;
var latestInputs = [];
function clickMe() {
let input = $("#input").val();
latestInputs.push(input);
$("#input").prop('value', '');
}
$('#input').bind('keydown', function(e) {
if (e.which === 38) {
$("#input").prop('value', previous());
} else if (e.which == 40) {
$("#input").prop('value', next());
} else if (e.which == 13) {
clickMe();
}
});
function previous() {
counter = (counter === 0) ? latestInputs.length - 1 : --counter;
return latestInputs[counter];
}
function next() {
counter = (counter === latestInputs.length - 1) ? 0 : ++counter ;
return latestInputs[counter];
}
</script>
</body>
</html>
it looks like your function on upArrow was triggered multiple times (3) every time you pressed that key, I moved it outside of the "keypress" binding and it stays on its own, and the problem no longer exists when i run the code
var singleValues;
var theInputsNumber = 19;
var latestInputs = new Array(20).fill("Latest");
function clickMe() {
singleValues = $("#input").val();
latestInputs.shift();
latestInputs.push(singleValues);
theInputsNumber = 19;
$("#output").append(singleValues);
$("#input").prop("value", "");
}
$(document).on("keypress", function (e) {
if (e.which === 13) {
clickMe();
}
});
$("#input").bind("keydown", function (e) {
var x = e.which || e.keyCode;
if (x === 38) {
$("#input").prop("value", latestInputs[theInputsNumber--]);
if (theInputsNumber === -1) {
theInputsNumber = 19;
}
}
});
<!DOCTYPE html>
<html>
<head>
<title>Think Fast Trivia</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="jqueryScript.js"></script>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="output" class="item1"></div>
<input autofocus type="text" name="input" id="input" />
<button id="send" onclick="clickMe()">Send</button>
</body>
</html>

Double tilde (~~) operator is removing decimal portion of number

So all this time I thought I was doing it wrong. But can jQuery read decimals? My first textbox has to multiply the input with .10, the second is .05. But I only get 1 as final result. How can I fix it?
<!DOCTYPE html>
<head>
<title>Test</title>
<script src="../js/jquery-1.11.1.min.js"></script>
<head>
<body>
<input id="first" type="text" />
<script>
$('#first').on('change', function () {
$(this).val($(this).val() * .10);
compute();
});
</script>
<input id="second" type="text" />
<script>
$('#second').on('change', function () {
$(this).val($(this).val() * .05);
compute();
});
</script>
<script>
function compute() {
var first = ~~$('#first').val();
var second = ~~$('#second').val();
var result = $('#result');
var grade = first + second;
result.val(grade);
}
</script>
<input id="result" type="text" readonly />
</body>
</html>
I believe you want to change compute() to this:
function compute() {
var first = parseFloat($('#first').val());
var second = parseFloat($('#second').val());
var result = $('#result');
var grade = first + second;
result.val(grade);
}

Showing Array result on an input text js

i am trying to show the price of each item on the price input, i am not able to make the function work. i am not sure how to write the string on or if i am even doing the function correctly. can you please help me? thanks!
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Price Calculation</title>
</head>
<body>
<Label>Choose Item</Label>
<select onChange=".......">
<option>Tomatoes</option>
<option>Lettuce</option>
<option>Potato</option>
<option>Carrots</option>
<option>Artichoke</option>
</select>
<br/>
<Label>Price</Label>
<input type="text" id="price" />
<br/>
<script type="text/javascript">
var veggy = new Array ()
veggy ["Tomatoes"] = 5.99
veggy ["Lettuce"] = 7.66
veggy ["Potato"] = 4.52
veggy ["Carrots"] = 2.13
veggy ["Artichoke"] = 10.58
function ()
{
var veggy = document.getElementById("price")
}
</script>
</body>
</html>
A couple things to change here:
You'd want an object with each choice as a key, and each price as a value - not an array
Call your function onchange and pass in the select element via this
//Make veggy an object
var veggy = {};
veggy["Tomatoes"] = 5.99;
veggy["Lettuce"] = 7.66;
veggy["Potato"] = 4.52;
veggy["Carrots"] = 2.13;
veggy["Artichoke"] = 10.58;
Change your select onChange:
<select onChange="getPrice(this);">
And your function:
function getPrice(select) {
document.getElementById("price").value = veggy[select.value];
}

Categories