Saving a Value, and adding to it - javascript

There are a few ways this can be asked, I'm trying to go with the easiest. Basically, I have two fields... one is to add a number, the other is to subtract. What I want, is when a number is input into either (let's just stick with the add input for now) and have it update at the bottom once the button "+" is pressed. I want that result to stay at the bottom, so when a new value is put into the add box and the button is pressed, it ADDS to the previous total. For the life of me, I can't figure this one out. Once resolved, I'll take care of the subtraction on my own, just need a push in the right direction. The current code is as follows.
<div id="entire">
<div id="content">
<input type="number" id="addInput" placeholder="0">
<button type="button" id="addBtn" onclick="add()">+</button>
<br>
<br>
<input type="number" id="subInput" placeholder="0">
<button type="button" id="subBtn" onclick="sub()">-</button>
<br>
<br>
<div id="totalAmt"></div>
<br>
<input type="button" id="clear" onclick="clearFields()" value="Clear">
<input type="button" id="reset" onclick="reset()" value="Reset">
</div>
</div>
function add() {
var addInput = document.getElementById("addInput").value;
var emptyValue = "";
var total = emptyValue + addInput;
document.getElementById("totalAmt").innerHTML = total;
}
function clearFields() {
document.getElementById("addInput").value = "";
document.getElementById("subInput").value = "";
}
function reset() {
document.getElementById("totalAmt").innerHTML = "";
}
A link to my codepen is below:
http://codepen.io/0ktane/pen/NNdbOq

Your problem is these two lines
var emptyValue = "";
var total = emptyValue + addInput;
when you are concatenating to a string, you get a string back.
Also, you are not even considering the previous value at first place.
Try this, updated pen
function add() {
var addInput = parseInt(document.getElementById("addInput").value); //parse the value to an integer first
var totalAmt = parseInt(document.getElementById("totalAmt").innerHTML); //parse the value to an integer first
totalAmt = isNaN(totalAmt) ? 0 : totalAmt; //if the value is NaN(not a number) reset it to 0
addInput = isNaN(addInput) ? 0 : addInput;//if the value is NaN(not a number) reset it to 0
document.getElementById("totalAmt").innerHTML = totalAmt + addInput ; //output the correct value
}

var total = 0;
function add() {
var addInput = parseInt(document.getElementById("addInput").value);
total = total + addInput;
document.getElementById("totalAmt").innerHTML = total;
}

Related

increment in the function name and id javascript

I have number of input types and buttons....every button on click increment the value in the relevant input types. But rather than creating a separate function for every button i want to do it by loop....where loop will increase in the function name and id......
<input type="number" id="s1"> <button onclick="increment_s1();">Add</button>
<input type="number" id="s2"> <button onclick="increment_s2()">Add</button>
<input type="number" id="s3"> <button onclick="increment_s3">Add</button>
here is JavaSc code
<script>
var i = 1;
for (i = 0; i < 5; i++) {
var data = 0;
document.getElementById("s"+i).innerText = data;
function ['increment_'+i]() {
data = data + 1;
document.getElementById("s"+i).placeholder = data;
i++;
}
}
</script>
You can't program the function name. You can set up a parameter in the function to make a difference. The param would be the identifier and you can put the whole input element id there.
After that, if you want to have the id s1, s2, and so on, you should initialize the i to start from 1 to 5 instead of 0 to less than 5.
Another thing is, you need to understand the role of placeholder and value attributes in input element. The placeholder works only when the value is empty and it doesn't count as the form value.
// This is for handling onclick
function increment(id) {
var elem = document.getElementById(id);
elem.value = parseInt(elem.value) + 1;
}
// This is to initialize the 0 values
for (var i = 1; i <= 5; i++) {
var data = 0;
document.getElementById("s"+i).value = data;
}
<input type="number" id="s1"> <button onclick="increment('s1');">Add</button>
<input type="number" id="s2"> <button onclick="increment('s2')">Add</button>
<input type="number" id="s3"> <button onclick="increment('s3')">Add</button>
<input type="number" id="s4"> <button onclick="increment('s4')">Add</button>
<input type="number" id="s5"> <button onclick="increment('s5')">Add</button>
What if you would like to generate whole input and button with loops? You can get them by adding div and use the innerHTML, i.e.
// This is for handling onclick
function increment(id) {
var elem = document.getElementById(id);
elem.value = parseInt(elem.value) + 1;
}
var divElem = document.querySelector('div');
// Set up empty first
divElem.innerHTML = "";
for(var i=1; i<=5; i++) {
// Create elements here
var innerElem = `<input type="number" id="s${i}" value="0"> <button onclick="increment('s${i}')">Add</button>`;
// Push them all into innerHTML
divElem.innerHTML += innerElem;
}
<div></div>
You can try these two workarounds. Perhaps you may need to learn more about basic HTML elements and their attributes also Javascript.

How to check and return a message if no value entered

I'm still learning and am trying to simply take a number from an input, add 7 to it, and then display it on the webpage. It all works fine, but what I don't like is if you hit "submit" without entering a number, the HTML field shows "NaN" vs. a custom message, which is what I'd like to do.
Here's the code I have so far. What am I missing to capture that nothing was entered and return a different message?
function add7() {
let number = document.getElementById('num').value;
let addition = 7;
if (isNaN(number)){
document.getElementById("add").innerHTML ="Please enter a value";
}
else {
let original = parseInt(number,10);
num = addition + original;
document.getElementById("add").innerHTML = num;
}
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add"></p>
</div>
That is because an empty string actually returns true when passed to isNaN(), i.e. isNaN('') returns true.
To do that, you can simply move the check to the final step, a.k.a. evaluate the num variable instead:
function add7() {
let number = document.getElementById('num').value;
let addition = 7;
let original = parseInt(number, 10);
let num = addition + original;
if (isNaN(num)) {
document.getElementById("add").innerHTML = "Please enter a value";
return;
}
document.getElementById("add").innerHTML = num;
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add">
</p>
</div>
Alternatively, you can also simply parse the input element's value directly: it will inform you if it is not a number right away:
function add7() {
let number = parseInt(document.getElementById('num').value, 10);
if (isNaN(number)) {
document.getElementById("add").innerHTML = "Please enter a value";
return;
}
let addition = 7;
let num = addition + number;
document.getElementById("add").innerHTML = num;
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add">
</p>
</div>

Issues outputting text via JavaScript

https://codepen.io/kev_daddy/pen/MMWEMG
I am building a form that is meant to update the difference between two values in real time (ie without refreshing the page). It is comprised of multiple fields, but ultimately I'll be getting the sum of two values, and displaying this using HTML.
The entire thing appears to work as intended until I get to the function that is meant to display the sum in html.
The intention is that the result (a hidden field) is shown as plain text in output. It doesn't trigger on the onset, however if i punch in an extra character using my keyboard, the event is finally heard and the text shows. up.
I am sure that I am missing something, but how do I ensure that the sum is outputted?
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0;
var y = document.getElementById('content').value || 0;
var result = document.getElementById('result');
var myResult = parseInt(x) + parseInt(y);
result.value = myResult; }
var input = document.getElementById("result");
var output = document.getElementById("output"); input.addEventListener("input", function() {
output.innerText = this.value;
});
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
<hr>
<p>You can earn <span id="output"></span> more!
There is no input event on span. You can create a separate function and pass the value of the calculation to this function whose responsibility will be to update the span text content
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0;
var y = document.getElementById('content').value || 0;
var result = document.getElementById('result');
var myResult = parseInt(x) + parseInt(y);
result.value = myResult;
updateText(myResult)
}
function updateText(val) {
document.getElementById("output").innerText = val;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
<hr>
<p>You can earn <span id="output"></span> more!

Sort Number in a Textbox on Ascending order using keypress function - HTML

Hi I'm new in the community.
I am trying to create a simple page where in there are 3 textbox. 1st text box is where the number will be entered. For 2nd and 3rd textbox is where the result will be shows on a different format as soon as the numbers are entered from the 1st textbox. 2nd text box should show the number with a comma which I was able to do. Example: As soon as I enter a number on the first text box 22 55 01 02 the 2nd text box will show 22,55,01,02 however on the 3rd textbox it should show the same number from 2nd textbox but on Ascending order which I weren't able to do so. Tried searching for a solution already but to now avail. Maybe I am just missing something. Any help will be very much appreciated.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// code for textbox 3 that didn't work
//function sortAscending(a, b)
//{return a - b;
// }
//var points = boxx3.value;
//points.sort(sortAscending);
//document.getElementById("boxx3").innerHTML = points;
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<body>
<B><br><center>PASTE HERE</br>
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()"
onKeyUp="boxx1KeyPress()">
<br>
<input type="button" Value="Clear Field" onClick="ClearField()">
<br>
<br>11x5 GAMES</BR>
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>Keno Games</br>
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend" onClick="points.sort(sortAscending)">
</body>
It's actually incredibly simple to sort numbers in JavaScript. All you need to do is:
Split the initial string into an array with .split(" ") (splitting on a space).
Sort the numbers with .sort().
Join the numbers back to a string with .join().
Keep in mind that as the output box is an <input>, you'll need to use .value instead of .innerHTML:
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// Fixed code for sorting the numbers
var points = boxx1.value.split(" ");
document.getElementById("boxx3").value = points.sort().join();
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<body>
<br>
<center>
<b>PASTE HERE</b>
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()" onKeyUp="boxx1KeyPress()">
<br>
<br>
<input type="button" Value="Clear Field" onClick="ClearField()">
<br>
<br>
11x5 GAMES
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>
Keno Games
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend">
</center>
</body>
Also note that you had some slightly invalid HTML in your above snippet (primarily that <br> is a void element, so the tag self-closes and thus </br> is not valid). I've cleaned up the HTML in my snippet above.
Hope this helps! :)
Your main issue is that you are trying to sort something that is still a string... you have to make your string into an array first.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// get an array from our string s
var arr = s.split(',');
arr.sort(); // note that for strings or ints, the default sort is ascending
document.getElementById("boxx3").innerHTML = arr.join(',');
}
I used the String.split method to get an array, separated at the commas, and the Array.join method to turn it back into a string after it was sorted.
Convert comma separated string into Array. Use array sort function and you done.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
}
function sortDisending() {
var numberArray = document.getElementById("boxx2").value.split(",");
numberArray.sort(function(a, b){return b-a});
document.getElementById("boxx3").value = numberArray;
}
function sortAsending() {
var numberArray = document.getElementById("boxx2").value.split(",");
numberArray.sort(function(a, b){return a-b});
document.getElementById("boxx3").value = numberArray;
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<B><br><center>PASTE HERE
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()"
onKeyUp="boxx1KeyPress()">
<br>
<br>
<br>11x5 GAMES
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>Keno Games
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend" onClick="sortAsending()">
<input type="button" Value="Descend" onClick="sortDisending()">
<input type="button" Value="Clear Field" onClick="ClearField()">

Compare a user inputted number with a randomly generated number in Javascript

I want to create a randomly generated number, ask the user to enter a number, then compare the two and then show a popup telling whether or not they match. This is my code
function myFunction() {
var num=document.getElementById("demo").innerHTML = Math.floor(1000 + Math.random() * 9000);
}
function myFunction1() {
var secondInput = document.getElementById("demo1").value;
if( num === secondInput)
{
window.alert("Same");
}
else
{
window.alert("Don't do that again cvv");
}
<button onclick="myFunction()">press the button to see the code</button>
<p id="demo"></p>
code: <input type="text" name="code" required/><br/><br/>
<button onclick="myFunction1()">Compare</button>
<p id="demo1"></p>
This code works. Please know that there were a couple of improvements:
You referenced to myFunction() before the javascript is loaded.
You need to keep the var num in global scope if you want to reference it in other places, without passing them as an argument.
When comparing values, make sure to select the right input field and to convert the value string to a Number.
var num;
function myFunction() {
num=document.getElementById("demo").innerHTML = Math.floor(1000 + Math.random() * 9000);
}
document.getElementById("button1").addEventListener('click', myFunction)
document.getElementById("button2").addEventListener('click', myFunction1)
function myFunction1() {
var secondInput = document.getElementById("demo1").value;
if( num === +secondInput) {
window.alert("Same");
}
else {
window.alert("Don't do that again cvv");
}
}
<button id="button1" >press the button to see the code</button>
<p id="demo"></p>
code: <input id="demo1" type="text" name="code" required/><br/><br/>
<button id="button2">Compare</button>
<p></p>
First you have to define num in the global scope to be accessable by the two functions and you have to make the first function just show the number without generating a new number every time.
var num;
function show() {
document.getElementById("demo").innerHTML = num;
}
function randomizeAndCompare() {
num = Math.floor(1000 + Math.random() * 9000);
var secondInput = document.getElementById("demo1").value;
if( num === secondInput){
window.alert("Same");
}
else{
window.alert("Don't do that again cvv");
}
}
<button onclick="show()">press the button to see the code</button>
<p id="demo"></p>
code: <input type="text" name="code" required/><br/><br/>
<button onclick="randomizeAndCompare()">Compare</button>
<p id="demo1"></p>
There are a couple of tings here.
First, myFunction1() isn't closed. You should also rename it to something more meaningful, like "compareValue()". That way it is easier to read the code.
You also aren't making a comparison of the two numbers in your compareValue()-function. Your 'num' variable isn't defined. You are also trying to extract the user input value from the button.
See my suggestion for changes:
function generateRandom() {
document.getElementById("demo").innerHTML = Math.floor(1000 +
Math.random() * 9000);
}
function compareValues() {
var num = document.getElementById("demo").innerHTML;
var input = document.getElementById("number").value;
if( num === input)
{
window.alert("Same");
}
else
{
window.alert("Don't do that again cvv");
}
}
HTML:
<button onclick="generateRandom()">press the button to see the code</button>
<p id="demo"></p>
code: <input id="number" type="text" name="code" required/><br/><br/>
<button onclick="compareValues()">Compare</button>
<p id="demo1"></p>

Categories