Getting an input from a form using JavaScript in html - javascript

I have created an input form in html and trying to get the value of this input field using JavaScript.
When I alert it, to check if it works, it returns an empty value. The code is below. What could be the problem?
var num1 = document.getElementById('numb1').value;
var num2 = document.getElementById('numb2').value;
var button = document.getElementsByTagName('button');
var show = document.getElementById('shows');
for (let i = 0; i < button.length; i++) {
if(button[i].id == 'plus'){
button[i].onclick = function (){
var a = num1 + num2;
alert(a);
}
}
}
<div class="container">
<div class="set">
<input type="text" id="numb1" placeholder="enter a number" >
<input type="text" id="numb2" placeholder="enter a number">
<div class="buttons">
<button id="plus">+</button>
<button id="min">-</button>
<button id="mult">*</button>
<button id="div">/</button>
</div>
<div class="show" id="shows"></div>
</div>
</div>

This because you have kept following lines outside the callback function:
var num1 = document.getElementById('numb1').value;
var num2 = document.getElementById('numb2').value;
So, num1 and num2 are initialized only once i.e. at page load-time. At this time both (num1 and num2) having empty value. Hence it not being initialized every time and showing and empty value.
Note:
Consider to parse input text into numeric values using parseInt() or parseFloat()
You should keep your JavaScript code in <script> tag.
Following is corrected code snippet:
var button = document.getElementsByTagName('button');
var show = document.getElementById('shows');
for (let i = 0; i < button.length; i++) {
if(button[i].id == 'plus'){
button[i].onclick = function (){
var num1 = document.getElementById('numb1').value;
var num2 = document.getElementById('numb2').value;
var a = parseFloat(num1 )+ parseFloat(num2);
alert(a);
}
}
}
<div class="container">
<div class="set">
<input type="text" id="numb1" placeholder="enter a number" >
<input type="text" id="numb2" placeholder="enter a number">
<div class="buttons">
<button id="plus">+</button>
<button id="min">-</button>
<button id="mult">*</button>
<button id="div">/</button>
</div>
<div class="show" id="shows"></div>
</div>
</div>

You need to get the value of the inputs when the button is clicked, not when the page loads.
var button = document.getElementsByTagName('button');
var show = document.getElementById('shows');
for (let i = 0; i < button.length; i++) {
if(button[i].id == 'plus'){
button[i].onclick = function (){
var num1 = parseFloat(document.getElementById('numb1').value);
var num2 = parseFloat(document.getElementById('numb2').value);
var a = num1 + num2;
alert(a);
}
}
}
The above code will get the value of the inputs when the button is clicked. I also presumed you would want the values converting to float, if this is not the case then remove the parseFloat function to make it:
var num1 = document.getElementById('numb1').value;
var num2 = document.getElementById('numb2').value;

Related

Math through multiple inputs

getting no errors but trying to loop through all the inputs and add them all to the total (var = paidTotal). The first input works but the rest don't when others are added with an add button. Something wrong with the loop?
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" id="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
var myNode = document.getElementById("userNumbers");
i=myNode.childNodes.length - 1;
if(i>=0){
myNode.removeChild(myNode.childNodes[i]);
x--;
}
});
});
function peoplePaid() {
var checkTotal = document.getElementById('check').value;
var personsCheck = document.getElementById('personsCheck').value;
var paidTotal = document.getElementById('paidTotal');
for(var i = 1; i < personsCheck.length; i+=1){
personsCheck[i] += paidTotal;
}
paidTotal.innerHTML = checkTotal - personsCheck;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$ <input type="text" id="check" value="" />
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<div class="">
<input type="text" id="personsCheck" name="person">
</div>
<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
<h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>
make it as class
<input type="text" class="personsCheck" name="person">
and access it by
var personsCheck = document.getElementsByClassName('personsCheck');
ids have to be unique. You'll only get one element from document.getElementById().
Try using a class instead, something like
var fieldInput = '<div><input type="text" name="persons" class="persons"/></div>';
and use document.getElementsByClassName('persons') to get an array of all of the input fields that have that class.
Your code logic is not something what you want to achieve.
I can not find any logic to use the input element with id=personsCheck.
First of all, you are appending input element with same id again and again which is invalid, because in a document id attribute must be unique. Use class attribute instead.
To get the total you can first get the elements with querySelectorAll(), theb use forEach() to loop through all of them to add one by one.
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" class="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
var myNode = document.getElementById("userNumbers");
i=myNode.childNodes.length - 1;
if(i>=0){
myNode.removeChild(myNode.childNodes[i]);
x--;
}
});
});
function peoplePaid() {
var checkTotal = Number(document.getElementById('check').value);
var persons = document.querySelectorAll('.persons');
var personsCheck = Number(document.getElementById('personsCheck').value)
var paidTotal = document.getElementById('paidTotal');
var total = 0;
persons.forEach(function(p){
total += Number(p.value);
});
paidTotal.textContent = checkTotal - total;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$ <input type="text" id="check" value="" />
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<div class="">
<input type="text" id="personsCheck" name="person">
</div>
<button onclick="peoplePaid()">Calculate</button>
<!--Paid Amount-->
<div>
<h3>Paid Amount: <span id="paidTotal"></span></h3>
</div>

Javascript - How to add results of two text boxes and display the result in a third?

I have two incrementally adding/subtracting values based on a button with onclick, as seen in below, and I attempted to have the outputs of these two boxes add into a third.
Javascript:
var i = 1;
function buttonClick() {
i++;
document.getElementById('inc').value = i;
}
function buttonClickA() {
i--;
document.getElementById('inc').value = i;
}
var w = 1;
function buttonClickC() {
w++;
document.getElementById('inc1').value = w;
}
function buttonClickD() {
w--;
document.getElementById('inc1').value = w;
}
function sum() {
var txtFirstNumberValue = document.getElementById('inc').value;
var txtSecondNumberValue = document.getElementById('inc1').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById("tot").value = result;
}
}
And the HTML:
<button onclick="buttonClick()">Add</button>
<input type="text" id="inc" value="0">
<button onclick="buttonClickA()">Subtract</button>
<button onclick="buttonClickC()">Add</button>
<input type="text" id="inc1" value="0">
<button onclick="buttonClickD()">Subtract</button>
<input type="text" id="tot" />
It adds a third textbox and the first two work fine, but no new output in the third, not sure what I am doing wrong.
You haven't called the sum() function.
call the sum() function for every button click.

how to store elements in array but by trucating leading zeros

function getResult(exp)
{
var result, num = [], signs = [];
//console.log("here" + exp.lastIndexOf(""));
parts = exp.split(/([+-/*])/);
for (var i = 0; i < parts.length; i++)
{
var item = parts[i].trim()
if (isNaN(item))
signs.push(item);
else
num.push(item);
}
console.log(num);
}
function maincalculation()
{
var txtprint = document.getElementById("texa");
if(!document.getElementById("texa").value)
{
}
else
{
var result = getResult(txtprint.value);
txtprint.value = result;
}
}
<html>
<body>
<div class = "textbox">
<!-- <input type="text" value="" id="tex" />
<input type="button" value="equal" onclick="equal()" id="add" />
<input type="button" value="click-count" onclick="click()" id="click" />
<p><input type="button" name="button" value="Saying Hello" id="hello" onclick="hello();"/></p> -->
<br><br>
<input types="text" id="texa">
<input type = "button" value = "calculate" onclick="maincalculation()" />
</div>
</body>
</html>
My code contain text-box it takes the whole String type by the user now i want to store the array elements separately in array. it stores perfectly as it is but i want to store array elements like by truncating leading zeros i have use regex function num = num.replace(/^[0]+/g,""); it eliminate all the leading zeros as i want but when user type only 0 it will eliminate 0 value too and stores the blank so is there any way that if user type suppose like [10+30+001+08*0/89] then this value must be store like this [10+30+1+8*0/89] truncating all leading zeros but not the single zero value.
Example for my comment:
var regex = new RegExp('0*(?=[0-9])+', 'g');
console.log('0'.replace(regex, '')); //0
console.log('0000'.replace(regex, '')); //0
console.log('01'.replace(regex, '')); //1
console.log('00106'.replace(regex, '')); //106
console.log('4'.replace(regex, '')); //4
console.log('10+30+001+08*0/89'.replace(regex, ''));
function getResult(exp) {
var result, num = [], signs = [];
parts = exp.split(/([+-/*])/);
for (var i = 0; i < parts.length; i++) {
var item = parts[i].trim()
if (isNaN(item))
signs.push(item);
else
num.push(+item.replace(regex,''));
}
console.log(num);
}
function clickMe() {
getResult($('#calculation').val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="calculation" value="10+30+001+08*0/89"/>
<button onclick="clickMe()">Get result</button>

simple addition using javascript

This statement document.getElementById=count is getting executed and showing result inside while loop only. outside the while loop this statement doesn't show any result what is the reason?
Here is my Screenshot
function add() {
var x = document.getElementById("txt1").value;
var count = 0;
x = x.match(/[+\-]*(\.\d+|\d+(\.\d+)?)/g) || [];
while (x.length) {
count += parseFloat(x.shift());
}
document.getElementById("demo1").innerHTML = count;
}
<input type="text" id="txt1" name="txt1" />
<button onclick="add()">Try</button>
<p id="demo1">para</p>

Why does my value keep returning as "NaN"?

Here is the link to the jsbin.
I was almost finished with my project (I thought I was) and then I tested it out. It is supposed to add buttons with the chosen title of the task and the number of points it awards. Every time the button is clicked the points would be added on to the "Points" section and every 500 points my "Level" would increase.
Upon finishing it, it worked. Then I went to clear the localStorage since that's what I used to save the information, but I wanted to start over. When I did that, the 'Points' section, or 'results' value, keeps returning as "NaN". The code is exactly the same as it was when it worked. Can someone please tell me how to fix this problem, thank you in advance.
Here is the code. (Used bootstrap for CSS)
HTML
<center>
<br>
<h2> Add task </h2>
<div class='well' style='width:500px' id="addc">
<div id="addc">
<input class='form-control' style='width:450px' id="btnName" type="text" placeholder="New Task" /><br>
<input class='form-control' style='width:450px' id="btnPoints" type="text" placeholder="Points" /><br>
<button id="addBtn">Add</button>
</div> </div>
<div class='well' style='width:230px' id="container">
</div>
<hr style="width:400px;">
<h3>Points </h3>
<div id="result">0</div>
</div>
<hr style="width:400px;">
<div style="width:400px;">
<h3>Level
<p id='lvl'>0</p>
</div>
<hr style="width:400px;">
</center>
JavaScript
var res = document.getElementById('result');
res.innerText = localStorage.getItem('myResult');
var level = document.getElementById('lvl');
level.textContent = localStorage.getItem('myLevel');
var btns = document.querySelectorAll('.btn');
for(var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
}
var addBtn = document.getElementById('addBtn');
addBtn.className = "btn btn-default";
addBtn.addEventListener('click', function() {
var container = document.getElementById('container');
var btnName = document.getElementById('btnName').value;
var btnPoints = parseInt(document.getElementById('btnPoints').value);
if(!btnName)
btnName = "Button ?";
if(!btnPoints)
btnPoints = 50;
var newBtn = document.createElement('button');
var newPnt = document.createElement('span');
newBtn.className = 'btn btn-danger';
newBtn.innerText = btnName;
newBtn.setAttribute('data-points', btnPoints);
newBtn.addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
newPnt.className = 'label';
newPnt.innerText = "+" + btnPoints;
container.appendChild(newBtn);
container.appendChild(newPnt);
});
function addToResult(pts) {
var result = document.getElementById('result');
result.innerText = parseInt(result.innerText) + parseInt(pts);
var lvl = 0;
var a = 100;
while (result.innerText > 5*a) {
lvl+=1;
a+=100;
}
document.getElementById('lvl').innerText = lvl;
var res = document.getElementById('result');
localStorage.setItem("myResult", res.innerText);
var level = document.getElementById('lvl');
localStorage.setItem("myLevel", level.textContent);
}
You were parsing result.innerText as a number, but its value, initially, was actually either NaN or nothing, both which end up being NaN. One fix is to just check if it parsed to a number, and if it didn't, fall back to 0.
I just basically changed that and removed some getElementByIds that, in my opinion, were redundant, check the addToResult function:
http://jsfiddle.net/owc26a0p/1/
function addToResult(pts) {
// NaN is falsy, so you can just use || to make a fallback to 0
var result = parseInt(resDiv.innerText, 10) || 0,
lvl = 0,
a = 100;
result = result + parseInt(pts, 10) || 0;
while (result > 5 * a) {
lvl += 1;
a += 100;
}
resDiv.innerText = result;
levelDiv.innerText = lvl;
localStorage.setItem("myResult", result);
localStorage.setItem("myLevel", levelDiv.textContent);
}
I ended up using jsFiddle since I couldn't always get jsBin to save my changes. Good luck.

Categories