i am trying to do simple multiply and divide using javascript and dom here are the codes
javascript
"use strict";
console.groupCollapsed("exDom1");
const fnum = document.getElementById("first-number").value;
const snum = document.getElementById("second-number").value;
function multiplyBy(number1, number2) {
document.getElementById("result").innerHTML = number1 * number2;
}
function divideBy(number1, number2) {
document.getElementById("result").innerHTML = number1 / number2;
}
console.groupEnd("exDom1");
for some reason i keep getting Nan for everything i try ,thanks in advance
this is the html
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JavaScript: DOM </title>
<script defer src="ex1.js"></script>
</head>
<body>
<h1>JavaScript</h1>
<p>In this exercise you have to define two functions in JavaScript to calculate multiplication and division of two
numbers. </p>
<ul>
<li>The result has to be written below the buttons in the section which id is "result".</li>
<li>Ues document.getElementById("result").innerHTML to set the value in the result section. </li>
<li>Use document.getElementById("first-number").value to get the value of the first number. </li>
<li>Use document.getElementById("second-number").value to get the value of the second number.</li>
</ul>
<div>
<p>1st Number :
<input type="text" id="first-number">
</p>
<p> 2nd Number:
<input type="text" id="second-number">
</p>
</div>
<input type="button" onClick="multiplyBy()" value="Multiply" />
<input type="button" onClick="divideBy()" value="Divide" />
<p>The Result is :
<span id="result"></span>
</p>
</body>
</html>
thanks in advance <3
You are calling the functions 'multiplyBy' and 'divideBy' without any parameters assigned. What you want to do is get 'first-number' and 'second-numbers' values in the function and then use the values.
Something like this:
"use strict";
console.groupCollapsed("exDom1");
function multiplyBy() {
const fnum = document.getElementById("first-number").value;
const snum = document.getElementById("second-number").value;
document.getElementById("result").innerHTML = fnum * snum;
}
function divideBy() {
const fnum = document.getElementById("first-number").value;
const snum = document.getElementById("second-number").value;
document.getElementById("result").innerHTML = fnum / snum;
}
console.groupEnd("exDom1");
You get the values of the input fields when the page first loads, and at that point, they are empty (NaN: Not a Number). You must get the values at the time that the button is clicked. Also, your functions use arguments that are never passed (again, not numbers). Instead, you can forego the parameters and just use the values at button click time.
Additionally, avoid .innerHTML whenever you can as there are security and performance implications to using it. And, since you aren't processing any HTML strings, you certainly have no need for it. Instead, use .textContent.
const fnum = document.getElementById("first-number");
const snum = document.getElementById("second-number");
const result = document.getElementById("result");
function multiplyBy() {
result.textContent = fnum.value * snum.value;
}
function divideBy() {
result.textContent = fnum.value / snum.value;
}
console.groupEnd("exDom1");
<div>
<p>1st Number:<input type="text" id="first-number"></p>
<p>2nd Number:<input type="text" id="second-number"></p>
</div>
<input type="button" onClick="multiplyBy()" value="Multiply">
<input type="button" onClick="divideBy()" value="Divide">
<p>The Result is : <span id="result"></span></p>
Lastly, you should not be using inline HTML event attributes like onclick. This is a 25+ year old technique that we used in the earliest days of web scripting when we didn't have any standards and using this technique in 2021 has real implications for the execution of your code. Instead, follow modern standards and separate your JavaScript from your HTML and use .addEventListener() to wire up events.
const fnum = document.getElementById("first-number");
const snum = document.getElementById("second-number");
const result = document.getElementById("result");
// The same event handler can be used for both buttons
document.querySelector("input[value='Multiply']").addEventListener("click", doMath);
document.querySelector("input[value='Divide']").addEventListener("click", doMath);
// All DOM event handlers are automatically passed a
// reference to the event that triggered them
function doMath(event) {
// We can get a reference to the actual element that
// triggered the event with event.target. So, depending
// on which event.target was clicked, do the right math
if(event.target.value === "Multiply"){
result.textContent = fnum.value * snum.value;
} else if(event.target.value === "Divide"){
result.textContent = fnum.value / snum.value;
}
}
<div>
<p>1st Number:<input type="text" id="first-number"></p>
<p>2nd Number:<input type="text" id="second-number"></p>
</div>
<input type="button" value="Multiply">
<input type="button" value="Divide">
<p>The Result is : <span id="result"></span></p>
Related
I'm trying to return a value from a function so that it is displayed in HTML. It returns 0 on the HTML but it returns the correct input value on the alert message inside the function. Here is the code I have:
<body>
<p>Number of bags: </p>
<input type="number" id="numBagInputId">
<input type="submit" id="numBagSubmitId" onClick="myFunction()">
<p>You will need: </p>
<p id="bags"></p>
<p>grams.</p>
<script>
function myFunction() {
let dryAmount = document.getElementById("numBagInputId").value * 921;
alert (dryAmount);
return dryAmount;
}
let bagTotal = myFunction();
document.getElementById("bags").innerHTML = bagTotal;
</script>
</body>
Since you haven't defined any event listener methods, myFunction() is called first. However, the value 0 is returned because data has not yet been entered into the <input> element. To prevent this, I assigned a value to the value attribute of the <input> element. The event listener method of the <input> element is used to update the value within the program.
const inputElement = document.getElementById('numBagInputId');
function myFunction() {
let dryAmount = inputElement.value * 921;
console.log(`Result: ${dryAmount}`)
return dryAmount;
}
function update(){
let bagTotal = myFunction();
document.getElementById("bags").innerHTML = bagTotal + " this is the bag total value";
}
inputElement.addEventListener('input', function(){
update();
});
update();
<p>Number of bags: </p>
<!-- The value attribute is assigned a default value. -->
<input type="number" id="numBagInputId" value="10">
<input type="submit" id="numBagSubmitId" onClick="myFunction()">
<p>You will need: </p>
<p id="bags"></p>
<span>grams</span>
update your script as given in ss.
https://i.stack.imgur.com/HWBKq.jpg
I want to add two zeros to any number entered in a textbox when submitted.
For instance, if i enter 34 in a textbox and click on submit, it should be saved as 3400.
Could this be done on the fly too?
Depends on what you want to do after the submit. Especially: Do you want to interpret this as a number and simply multiply by 100 (34 * 100) or do you want to simply append something to the value? ("34" + "00")?
In the first case you would do this:
<input id="value" type="number" value="34"/>
<br>
<button onclick="submit()">Submit</button>
<script>
function submit() {
const input = document.getElementById("value");
const value = input.attributes.value;
input.value = parseInt(input.value) * 100;
}
</script>
In the second case this:
<input id="value" type="number" value="34"/>
<br>
<button onclick="submit()">Submit</button>
<script>
function submit() {
const input = document.getElementById("value");
const value = input.attributes.value;
input.value = input.value.toString() + '00';
}
</script>
A bit vague, but it sounds like you're looking for something like the following.
// Gather each element from the HTML, so you can access its input or update its display:
const input = document.getElementById('numberInput');
const button = document.getElementById('submit');
const display1 = document.getElementById('display1');
const display2 = document.getElementById('display2');
// Add a click event to the button, which gathers the text field value, ensures it's a number, and updates the display as requested:
button.addEventListener('click',() => {
const value = input.value;
// This if statement ensures that only numbers will be suffixed with be suffixed with two zeros:
if (isNaN(value)) {
alert('Please enter a valid number');
return;
}
// Update the display span's contents as requested. There are many ways of doing this. Here are a few;
// Here I'm taking the submitted value, and nesting it inside a string, alongside the two zeros. In cases of Infinity or .100, the result will still be the input suffixed with two zeros:
display1.innerHTML = `${value}00`;
// This method, on the other hand, will simply move the decimal to columns:
display2.innerHTML = value * 100;
});
<p>
Display 1: <span id="display1"></span>
</p>
<p>
Display 2: <span id="display2"></span>
</p>
<input type="text" id="numberInput">
<button id="submit">Submit</button>
You could always set an event listener that changes the number on exit of the form element, so something like this:
document.addEventListener('DOMContentLoaded', watchNums);
function watchNums() {
document.removeEventListener('DOMContentLoaded', watchNums);
Array.from(document.getElementsByClassName('number')).map(
number => {
number.addEventListener('blur', _ => {
number.value = parseInt(number.value) * 100;
})
}
)
}
<body>
<form action="/endpoint.htm" method="POST">
<input type="number" name="number-input" class="number">
<input type="number" name="other-number-input" class="number">
<button type="submit">Submit Numbers</button>
</form>
</body>
I have created a simple calculator that takes variable #1 and variable #2 and multiplies them to generate a result.
When I change variable #1 the result instantly changes. However, when I change variable #2 the result remains unchanged.
How do I reconfigure my code so that the result instantly changes when either variable is altered?
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h6>Variable #1</h6>
<input id="var1">
<h6>Variable #2</h6>
<input id="var2">
<h6>Result</h6>
<input readonly="readonly" id="result">
<script>
$(document).ready(function(){
var mt=$("#var1");
mt.keyup(function(){
var total=isNaN(parseInt(mt.val()* $("#var2").val())) ? 0 :(mt.val()* $("#result").val())
$("#result").val(total);
});
});
</script>
You have many things going wrong here,
you need to bind keyup event in var1 textbox and var2 textbox both
Also, your multiply formula is also wrong. Here is the desire code:
$(document).ready(function(){
var mt=$("#var1,#var2");
mt.keyup(function(){
debugger;
var total= 0;
if(!isNaN(parseInt($("#var1").val())* parseInt(parseInt($("#var2").val())))){
total= parseInt($("#var1").val())* parseInt(parseInt($("#var2").val()));
}
$("#result").val(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h6>Variable #1</h6>
<input id="var1">
<h6>Variable #2</h6>
<input id="var2">
<h6>Result</h6>
<input readonly="readonly" id="result">
Consider binding keyup events on both #var1 and #var2 inputs using the following jQuery syntax #var1, #var2 to achieve this desired behaviour, as shown:
$(document).ready(function(){
// Select and bind keyup event to both "var" input elements using
// this syntax
$('#var1, #var2')
.keyup(function(){
// Adjust your keyup handler to perform calculation when keyup
// occurs on either input field
var total= 0;
if(!isNaN(parseInt($("#var1").val())* parseInt($("#var2").val()))){
total = parseFloat($("#var1").val())* parseFloat($("#var2").val());
}
$("#result").val(total);
});
});
I just want to answer in vanilla Javascript for future reference of the problem..
I make var1,var2 class="input", then querySelect them both, then loop them, so that when you put any number to them, their value(product) will be produce in the id="result"
if you did not put any number to them, the default value is zero(0) for both of them, so let say, you only put 10 to var1, then the output will only be 10, and if you put non numeric character, then the output is NaN.
let input = document.querySelectorAll(".input");
let var1 = document.querySelector("#var1");
let var2 = document.querySelector("#var2");
let output = document.querySelector("#result");
function result(var1=0,var2=0) {
output.value = Number(var1)*Number(var2);
}
for(let i=0;i<input.length;i++)
{
input[i].addEventListener(`keyup`,()=>result(var1.value,var2.value))
}
<h6>Variable #1</h6>
<input id="var1" class="input">
<h6>Variable #2</h6>
<input id="var2" class="input">
<h6>Result</h6>
<input readonly="readonly" id="result">
By the way you can also make the code much shorter by instead of putting the id var1,var2 value, you can instead just put the input class[0], and [1] it's the same..
so it can also be done this way.
let input = document.querySelectorAll(".input");
let output = document.querySelector("#result");
function result(var1=0,var2=0) {
output.value = Number(var1)*Number(var2);
}
for(let i=0;i<input.length;i++)
{
input[i].addEventListener(`keyup`,()=>result(input[0].value,input[1].value))
}
<h6>Variable #1</h6>
<input id="var1" class="input">
<h6>Variable #2</h6>
<input id="var2" class="input">
<h6>Result</h6>
<input readonly="readonly" id="result">
By the way if you want to follow the same logic by using ternary operator,
let's follow his example, by using ternary operator,
change the result function to this.
function result(var1=0,var2=0) {
(var1*var2 ===0)? output.value=0: output.value=Number(var1) * Number(var2);
}
I'm trying to use a input number type to update how many times a particular amount of content is added to the page. In the example I'm doing it with a p tag but in my main model I'm using it on a larger scale with multiple divs. However, I can't seem to be able to get this to work. If someone can see where I'm going wrong that would be very helpful.
function updatePage() {
var i = document.getElementById("numerInput").value;
document.getElementById("content").innerHTML =
while (i > 1) {
"<p>Content<p/><br>";
i--;
};
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update" onclick="updatePage()">
<div id="content">
<p>Content
<p>
<br>
</div>
First, you have quite a few problems that need addressing:
You are setting the .innerHTML to a while loop, which is invalid because a loop doesn't have a return value. And, inside your loop, you just have a string of HTML. It isn't being returned or assigned to anything, so nothing will happen with it.
You've also mis-spelled the id of your input:
document.getElementById("numerInput")
Also, don't use inline HTML event attributes (i.e. onclick) as there are many reasons not to use this 20+ year old antiquated technique that just will not die. Separate all your JavaScript work from your HTML.
Lastly, your HTML is invalid:
"<p>Content<p/><br>"
Should be:
"<p>Content</p>"
Notice that in addition to fixing the syntax for the closing p, the <br> has been removed. Don't use <br> simply to add spacing to a document - do that with CSS. <br> should be used only to insert a line feed into some content because that content should be broken up, but not into new sections.
Now, to solve your overall issue, what you should do is set the .innerHTML to the return value from a function or, more simply just the end result of what the loop creates as I'm showing below.
// Get DOM references just once in JavaScript
let input = document.getElementById("numberInput");
let btn = document.querySelector("input[type='button']");
// Set up event handlers in JavaScript, not HTML with standards-based code:
btn.addEventListener("click", updatePage);
function updatePage() {
var output = ""; // Will hold result
// Instead of a while loop, just a for loop that counts to the value entered into the input
for (var i = 0; i < input.value; i++) {
// Don't modify the DOM more than necessary (especially in a loop) for performance reasons
// Just build up a string with the desired output
output += "<p>Content</p>"; // Concatenate more data
};
// After the string has been built, update the DOM
document.getElementById("content").innerHTML = output;
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update">
<div id="content">
<p>Content</p>
</div>
And, if you truly do want the same string repeated the number of times that is entered into the input, then this can be a lot simpler with string.repeat().
// Get DOM references just once in JavaScript
let input = document.getElementById("numberInput");
let btn = document.querySelector("input[type='button']");
// Set up event handlers in JavaScript, not HTML with standards-based code:
btn.addEventListener("click", updatePage);
function updatePage() {
// Just use string.repeat()
document.getElementById("content").innerHTML = "<p>Content</p>".repeat(input.value);
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update">
<div id="content">
<p>Content</p>
</div>
As #ScottMarcus pointed out you had the following issues:
While Loops do not need a ; at the end of while(args) {}
Your .innerHTML code was in the wrong place
You had a typo in getElementById("numerInput") which I changed to getElementById("numberInput")
Code
function updatePage() {
// Get input value
var numberInput = document.getElementById("numberInput").value;
// Will be used to store all <p> contents
var template = "";
while (numberInput > 0) {
// Add all contents into template
template += "<p>Content<p/><br>";
numberInput--;
}
// Append upon clicking
document.getElementById("content").innerHTML = template;
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update" onclick="updatePage()">
<div id="content">
</div>
I am a beginner and I have the following problem/code for the main body:
<body>
<form action="#">
<input type="text" id="start" />
=
<input type="text" id="finish" />
</form>
<script>
$(function() {
var cVal = $("#start").val();
var fVal = $("#finish").val();
});
</script>
</body>
With two text boxes, I would like the value entered in the celsius text box to be converted into fahrenheit in the other text box. I have tried to use the
keyup()
function but failed to produce the results I want.
typing 15 into the celsius box should result in 59 in fahrenheit. I understand that .val() does not take any arguments, so where would I do the computation for converting the numbers? And how can I incorporate keyup?
Any help is appreciated!
The val function does take arguments, you can pass it the new value and it will update textbox contents. Click the link on val, it will take you to the jQuery documentation, where all possible calls are explained. Or see the example below.
function fahrenheitToCelsius(fahrenheit) {
var val = 0;
// perform calculation
return val;
}
function celsiusToFarenheit(celsius) {
var val = 0;
// perform calculation
return val;
}
$(function() {
$("#start").on('keyup', function() {
$("#finish").val(celsiusToFarenheit($(this).val()));
});
$("#finish").on('keyup', function() {
$("#start").val(fahrenheitToCelsius($(this).val()));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
<input type="text" id="start" /> Celsius
=
<input type="text" id="finish" /> Fahrenheit
</form>
This is such a simple thing to do, jQuery is not needed at all, and because you haven't tagged jQuery here comes a plain javascript solution.
What you need to do is the add a keyup trigger on each of the input elements.
To grab our input fields we use document.getElementById(id), we use this because you've added the id attribute to your fields (it's faster than the latter method I'm mentioning). We could've used document.querySelector(selector) to get our input fields to. If you had used name="celsius" on the celsius field, we could've used document.querySelector('input[name="celsius"]') to grab that element.
What we need to do next is to an a keyup trigger to both our input fields. This is done with element.onkeyup = function() {}, in each of those functions we calculate the value for the other field.
var celsius = document.getElementById('start'),
fahrenheit = document.getElementById('finish');
celsius.onkeyup = function() {
fahrenheit.value = this.value * 9/5 + 32;
}
fahrenheit.onkeyup = function() {
celsius.value = (this.value - 32) * 5/9;
}
<form action="#">
<input type="text" id="start" /> Celsius
=
<input type="text" id="finish" /> Fahrenheit
</form>
The jQuery .val() function is an overload function which means it takes 0 up to 1 argument and it's effect varies on the number of arguments passed.
As you can see in my example calling celsiusInput.val() just returns the current value of the field. However if you use it like this farenheitOutput.val(farenheit) the current value of the input is overwritten by the variable passed.
const updateFarenheit = () => {
// find the input and output in the dom by their id
const celsiusInput = $("#start");
const farenheitOutput = $("#finish");
// get the input value
const celsius = celsiusInput.val();
const farenheit = celsius * 9 / 5 + 32;
// update the farenheit output
farenheitOutput.val(farenheit);
}
// this function runs when all js is loaded aka. "document ready"
$(document).ready(function() {
// get input field by id
const celsiusInput = $("#start");
// we pass the updateFarenheit function we defined before as the function which should run
// as soon as the keyup event occures on our celsiusInput field
celsiusInput.keyup(updateFarenheit);
});
<html lang="">
<head>
<meta charset="utf-8">
<title>Celsius to Farenheit</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form action="#">
<input type="text" id="start" /> =
<input type="text" id="finish" />
</form>
</body>
</html>