Adding two numbers together using HTML and Javascript - javascript

I'm trying to understand how to tie code and webpages together and stuff, so I mocked up this basic HTML page to add two numbers together using Javascript.
const first_n = document.getElementById("fnumber")
const second_n = document.getElementById("snumber")
window.onload = function solve(first_n, second_n) {
var solved = first_n + second_n;
document.getElementById("solution").innerHTML = solved
}
<body>
<form action="javascript:solve()">
<label for="fnumber">First n:</label><br>
<input type="number" id="fnumber"><br>
<label for="snumber">Last n:</label><br>
<input type="number" id="snumber">
<input type="submit" value="Solve">
</form>
<p id="solution"></p>
</body>
I know my nomenclature is a mess, don't judge. I just wanna see what I can get to work.
Thoughts on why this isn't working?

You need to call the solve function on click of the submit button. Secondly get the value of the input element inside the function
function solve(e) {
e.preventDefault();
const first_n = document.getElementById("fnumber").value
const second_n = document.getElementById("snumber").value
var solved = Number(first_n) + Number(second_n);
document.getElementById("solution").innerHTML = solved
}
<form>
<label for="fnumber">First n:</label><br>
<input type="number" id="fnumber"><br>
<label for="snumber">Last n:</label><br>
<input type="number" id="snumber">
<input type="submit" value="Solve" onclick='solve(event)'>
</form>
<p id="solution"></p>

The window.onload event runs only once and that is when the page loads. At this time, the user has probably not entered any data, hence your fnumber and snumber will not contain any user entered values.
It would be better to trigger your solve function differently, for example associated with a button click via event listener or html on<> attributes

I have checked your code, please find the below fix.
const first_n = document.getElementById('fnumber');
const second_n = document.getElementById('snumber');
function solve() {
var solved = parseFloat(first_n.value) + parseFloat(second_n.value);
document.getElementById('solution').innerHTML = solved;
}
In your code you are not getting the input Values.
You will call the solve function when you click on the submit button and not on page load.

Solution
You need to convert the input values from a string to a number. by default the input values are stings.
const solve = e => {
e.preventDefault()
const firstNumber = Number(document.querySelector('#fnumber').value)
const secondNumber = Number(document.querySelector('#snumber').value)
document.querySelector('#solution').innerText = firstNumber + secondNumber
}
<form>
<label for="fnumber">First n:</label><br>
<input type="number" id="fnumber"><br>
<label for="snumber">Last n:</label><br>
<input type="number" id="snumber">
<input type="submit" value="Solve" onclick='solve(event)'>
</form>
<p id="solution"></p>
Example of input default data type (default is string)
console.log(document.querySelector("#data").value, typeof(document.querySelector("#data").value))
<input type="number" id="data" value="3">
Even when the input type is type="number" the datatype will be a string.
Bonus
You can declare the solve() function on window.onload if you use an arrow function (=>) to declare it, it will not work if you declare the function using a normal function declare (function solve() { ... }).
window.onload = solve = (e) => {
e.preventDefault()
const firstNumber = Number(document.querySelector('#fnumber').value)
const secondNumber = Number(document.querySelector('#snumber').value)
document.querySelector('#solution').innerText = firstNumber + secondNumber
}
<form>
<label for="fnumber">First n:</label><br>
<input type="number" id="fnumber" value="3"><br>
<label for="snumber">Last n:</label><br>
<input type="number" id="snumber" value="5">
<input type="submit" value="Solve" onclick='solve(event)'>
</form>
<p id="solution"></p>
This has the benefit of running once the window is loaded so as you can see we have set the values of the inputs by default to be 3 and 5 once the example loads it will calculate them without clicking the solve button.

Related

Is there a way to delete this tabs after creating them using cloneNode() in vanilla javascript?

I am trying to create a function in my vanilla JavaScript to delete tabs created by using cloneNode(true). Below is what i have tried but its not just working.
I created a form with class named secondSectionEmail; at the click of the button (+), the form is duplicated using cloneNode(). Each form is carrying a (x) button which is supposed to delete a particular tab. How do I achieve this please?
<form class="secondSectionEmail">
<button id="closeBtn">x</button>
<input type="email" id="recipient" placeholder="Enter Recipient Email">
<input type="text" placeholder="Subject"><br>
<textarea type="text" placeholder="Enter Message"></textarea>
<div class="upload">
<input type="file" multiple>
<button>Send Mail</button>
</div>
</form>
<br>
<br>
<button type="submit" id="arrow">+</button>
<script>
//script to add new tab
let addbutton = document.getElementById("arrow");
var i = 0;
addbutton.addEventListener("click", function (e) {
e.preventDefault();
let boxes = document.querySelector(".secondSectionEmail");
let closeC = document.getElementById('closeBtn');
var clone = boxes.cloneNode(true);
i++;
clone.className=`secondSectionEmail${i}`;
clone.classList.add(`mydiv`);
closeC.classList.add(`timzy${i}`);
boxes.after(clone);
})
//Script to delete tab
let deleteButton = document.querySelector(`.container`)
deleteButton.addEventListener("click", function (event) {
event.preventDefault()
var del = event.target.parentElement.className;
let newDel = document.getElementsByClassName(`${del}`);
let newDelete = Array.from(newDel)
console.log(newDelete)
})
</script>
Check the snippet below for solution to my question. I solved it two days after posting the question and i feel someone else might need the solution.
Solution:
else if(btnTarget==="closeBtn") {
wholeSection.parentElement.removeChild(wholeSection);
}

showing the result of multiply two input value in a div called result

I just want to show the result in this div ,i tried to use nodeValue instead value and call the finalCalc fun in js file but it show nothing when i click on the button.
var billValue=document.getElementById("dollars").value,
peopleValue=document.getElementById("people").value,
theResult=document.getElementById("result"),
calculateButton=document.getElementById("calculateButton");
function calculateTip(x,y){
var reso=x*y;
theResult.innerHTML=reso;
}
function finalCalc() {
calculateTip(billValue,peopleValue);
}
<form>
<label>how much was your bill?</label>
<label for ="dollars">$</label>
<input value ="0" type="text" id="dollars" placeholder="Bill Amount ">
<br>
<label for="people">How many people are sharing the bill?</label>
<input value ="0" type="text" id="people">
<button type="button" id="calculateButton" onclick()="finalCalc()">CALCULATE</button>
<div id="result"></div>
</form>
onClick is written as onClick="" instead of onclick()="", reworked your code a little, hope this helps.
var billValue = document.getElementById("dollars").value,
peopleValue = document.getElementById("people").value,
theResult = document.getElementById("result"),
calculateButton = document.getElementById("calculateButton");
function calculateTip(x, y) {
return x * y;
}
function finalCalc() {
theResult.innerHTML = calculateTip(billValue, peopleValue);
}
<button type="button" id="calculateButton" onClick="finalCalc()">CALCULATE</button>

Temperature Converter is giving me NaN

I need to make a temperature converter using forms and it has to have the ok button display the information and a clear button to clear all information.
This is what I have tried to do but it gives me NaN
function temperatureConverter(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;
}
<h2>Temperature Converter</h2>
Ok now my issue is that I need everything cleared even the Celsius data but I can't find a way for it to work
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<p>
<label>Fahrenheit</label>
<input id="inputFahrenheit" type="text" placeholder="Fahrenheit">
<input id= "button1" type= "button" value= "OK" onclick="temperatureConverter(this.value)">
<input id= "reset1" type= "reset" value= "Clear" onclick="temperatureConverter">
</p>
<p>Celcius: <span id="outputCelcius"></span></p>
Your code is not working because in your #button1 you wrote:
onclick="temperatureConverter(this.value)"
where this is not #inputFahrenheit but #button1. Therefore this.value actually equals to "OK".
To fix your problem, you need to change your temperatureConverter function to get value of #inputFahrenheit instead of using onclick="temperatureConverter(this.value)".
Similar situation happens in your #reset1, therefore your reset input will not work as well. You need to apply the same concept into your reset function, which I suggest to create a new function dedicated just for that.
Generally, it is not encouraged to use the same function to perform completely different actions.
function temperatureConverter(){
var input = document.getElementById('inputFahrenheit');
var value = input.value;
value = parseFloat(value);
var output = document.getElementById('outputCelcius');
output.innerHTML = (value - 32)/1.8;
}
function resetTemperature(){
/* clear the temperature */
console.log('clear');
}
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<p>
<label>Fahrenheit</label>
<input id="inputFahrenheit" type="text" placeholder="Fahrenheit">
<input id= "button1" type= "button" value= "OK" onclick="temperatureConverter()">
<input id= "reset1" type= "reset" value= "Clear" onclick="resetTemperature()">
</p>
<p>Celcius: <span id="outputCelcius"></span></p>
Here is the basics needed to get your code working. Basically it is simply just changing what value is passed to the temperatureConverter function. Before you were passing it the value of the button that was being clicked, not the value of the input element you were trying to read. Also, I'm unsure on this one as I didn't look it up, but the reset element wasn't working for me until I put your items inside of a <form> element.
function temperatureConverter(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;
}
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<form>
<p>
<label>Fahrenheit</label>
<input id="inputFahrenheit" type="text" placeholder="Fahrenheit">
<input id= "button1" type= "button" value= "OK" onclick="temperatureConverter(document.querySelector('#inputFahrenheit').value)">
<input id= "reset1" type= "reset" value= "Clear">
</p>
</form>
<p>Celcius: <span id="outputCelcius"></span></p>
Please note that most of the time, people don't like putting the event listener in the on[event] attributes, and many developers will prefer that you do something more like this:
// () => {} is something called Arrow function notation, if you didn't know it already.
document.addEventListener('DOMContentLoaded', () => {
function updateOutput(value) {
// make sure you do some checking to avoid XSS attacks.
document.querySelector('#output').innerHTML = value;
}
// keeps the form from submitting since we don't have an actual form handler and this is all front-end
document.querySelector('#converterForm').addEventListener('submit',(e)=>{
e.preventDefault();
});
document.querySelector('#convert').addEventListener('click', () => {
updateOutput(convertToCelsius(document.querySelector('#fahrenheit').value));
});
});
function convertToCelsius(f) {
if(typeof f == 'string') f = parseFloat(f, 10);
if(isNaN(f)) {
throw new Error('Invalid parameter passed to function convertToCelsius');
}
return (f-32) * 5 / 9;
}
<form id="converterForm" action="/">
<input type="number" id="fahrenheit" placeholder="Fahrenheit value">
<input type="button" id="convert" value="Convert to Celsius">
<input type="reset" value="Clear">
<div id="output">
</div>
</form>
Other than that, a good way to check why a function isn't working is to use console.log in your code and then check the Javascript browser (in Chrome you can get to it by hitting ctrl+shift+j, in Firefox I believe it's ctrl+shift+i).
can't see you using any form.
your function,
function temperatureConverter(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;
}
then,
<form id="tempConverter">
Convert: <input type="text" id="unit" name="converter" />
<input
type="button"
value="Submit"
onclick="temperatureConverter(document.getElementById('unit').value);"
/>
</form>
<p>Celcius: <span id="outputCelcius"></span></p>
apparently, if you console the value, you were obviously sending "OK" as param to the function(not the value of input field) which is NAN.

jquery - copy value of input from one form to another (form and input named the same)

I would like to copy the value from an input in one form to the value of an input(with the same name) of the next form down. The forms and inputs are named the same. All it needs to do is copy the value of the title input to the title input one form down.
<form>
<input name="file" value="1.xml">
<input name="title" id="title" value="Smith">
<input type="submit" id="copy-down" value="copy">
</form>
<form>
<input name="file" value="2.xml">
<input name="title" id="title" value="Anderson">
<input type="submit" id="copy-down" value="copy">
</form>
etc...
In this case when the top "copy" button is clicked I would like jquery to overwrite Anderson with Smith.
$('#title').attr('value'));
Gives me Smith but I'm not sure what to do with that value once I have it.
Change HTML to this:
<form>
<input name="file" value="1.xml">
<input name="title" id="title1" value="Smith">
<input type="submit" id="copy-down1" value="copy">
</form>
<form>
<input name="file" value="2.xml">
<input name="title" id="title2" value="Anderson">
<input type="submit" id="copy-down2" value="copy">
</form>
Javascript:
function copyHandler() {
var copyVal = document.getElementById("title1").value;
var replaceInput = document.getElementById("title2");
replaceInput.value = copyVal;
}
document.getElementById("copy-down1").onclick = function(){
copyHandler();
return false;
}
Some notes:
This is so straightforward in vanilla javascript that I didn't add the jQuery code.
You should never assign multiple elements to the same ID, class or name can be used for that purpose.
The return false; portion of the onclick function is necessary so that the form doesn't reload when you click your submit button.
Let me know if you have any questions.
you can try
$(document).ready(function(){
$('form').on('submit', function(e){
e.preventDefault();
var GetNameAttr = $(this).find('input:nth-child(2)').attr('name');
var GetTitleValue = $(this).find('input:nth-child(2)').val();
var NextFormNameAttr = $(this).next('form').find('input:nth-child(2)').attr('name');
if(NextFormNameAttr == GetNameAttr){
$(this).next('form').find('input:nth-child(2)').val(GetTitleValue );
}
});
});
Note: this code will change the second input value in next form with
the second input value of form you click if the name is same .. you
can do the same thing with the first input by using :nth-child(1)
Demo here
if your forms dynamically generated use
$('body').on('submit','form', function(e){
instead of
$('form').on('submit', function(e){
for simple use I create a function for that
function changeNextValue(el , i){
var GetNameAttr1 = el.find('input:nth-child('+ i +')').attr('name');
var GetTitleValue1 = el.find('input:nth-child('+ i +')').val();
var NextFormNameAttr1 = el.next('form').find('input:nth-child('+ i +')').attr('name');
if(NextFormNameAttr1 == GetNameAttr1){
el.next('form').find('input:nth-child('+ i +')').val(GetTitleValue1);
}
}
use it like this
changeNextValue($(this) , nth-child of input 1 or 2);
// for first input
changeNextValue($(this) , 1);
// for second input
changeNextValue($(this) , 2);
Working Demo

Javascript max and min not working

I am trying to create a page that lets the user enter three numbers, and have the max and min values printed below from the input. I've used both the Math.max/min functions and also tried an if statement but When I click submit nothing shows up. Some insight would be greatly appreciated, thanks!
function max() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
var z = document.getElementById("num3").value;
var maximum = Math.max(parseInt(x), parseInt(y), parseInt(z));
document.getElementById("max").innerHTML= maximum;
}
function min() {
var x = parseInt(document.getElementById("num1").value);
var y = parseInt(document.getElementById("num2").value);
var z = parseInt(document.getElementById("num3").value);
document.getElementById("min").innerHTML = Math.min(x,y,z);
}
And here is my html
<p>Enter First Number:</p>
<input type="text" name = "number1" id="num1"><br>
<p>Enter Second Number</p>
<input type="text" name = "number2" id="num2"><br>
<p>Enter third number</p>
<input type="text" name = "number3" id="num3"><br>
<input type="submit" value="Submit" onclick="max(); min(); "><br />
<p>Max =</p><p id ="max"></p><br />
<p>Min =</p><p id ="min"></p><br />
replace <input type="submit"/> to <button type="submit" value="" onclick="minmax();">Submit</button>
and add JS function:
function minmax() {
min();
max();
}
Your problem seems related to how you are attaching your event.
It works OK when I use:
document.querySelector( '[type="submit"]' ).addEventListener( 'click', function() {
max();
min();
}, false );
http://jsfiddle.net/yemxrmqq/
You just need to change the tag related to the button, instead of:
<input type="submit" value="Submit" onclick="max(); min(); "><br />
just put:
<button type="submit" value="Submit" onclick="max(); min()">Click</button><br />
None of the answers here tell you why your code didn't work.
Identifiers in inline listeners are first resolved as properties of the element on which they are placed. Input elements have a default max attribute, so within an inline listener, the identifier max will reference the input's max property. Hence in any document:
<input onclick="console.log(max)">
shows '' (i.e. empty string).
So you can either change the names of the functions to something more meaningful, or change the context from which they are called so that the identifiers aren't resolved on the element, and the OP code works. e.g.
<input type="submit" value="Submit" onclick="callBoth()">
and
function callBoth() {
max();
min();
}
Incidentally, an input type submit outside a form is just a button, so you should use:
<input type="button" ...>

Categories