simple addition using javascript - 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>

Related

How can i change on click function every time i got an error

I want first click to make the getNumberBtn to be getNumberBtnn
and the second one to get it back to getNumberBtn function.
When I click, the function run but doesn't change the onclick property
var equation = 0;
function getNumberBtn() {
document.getElementById("apply").onclick = getNumberBtnn();
equation = equation + x;
}
function getNumberBtnn() {
document.getElementById("apply").onclick = getNumberBtn();
equation = equation + x;
}
<div>
<input type="number" id="number" min="1" max="1000">
<button id="apply" onclick=getNumberBtn()>Apply</button>
</div>
When you assign the function to onclick, you are actually calling the function and thus creating an infinite recursive.
You can just assign the function name to onclick -
var equation = 0;
function getNumberBtn() {
document.getElementById("apply").onclick = getNumberBtnn;
equation = equation + document.getElementById("number").value;
console.log('Called getNumberBtn');
}
function getNumberBtnn() {
document.getElementById("apply").onclick = getNumberBtn;
equation = equation + document.getElementById("number").value;
console.log('Called getNumberBtnn');
}
<div>
<input type="number" id="number" min="1" max="1000">
<button id="apply" onclick=getNumberBtn()>Apply</button>
</div>
But I would suggest you use DOM event registration instead using addEventListener and removeEventListener-
var equation = 0;
var apply = document.getElementById("apply");
apply.addEventListener('click', getNumberBtn);
function getNumberBtn() {
apply.removeEventListener('click', getNumberBtn);
apply.addEventListener('click', getNumberBtnn);
equation = equation + document.getElementById("number").value;
console.log('Called getNumberBtn');
}
function getNumberBtnn() {
apply.removeEventListener('click', getNumberBtnn);
apply.addEventListener('click', getNumberBtn);
equation = equation + document.getElementById("number").value;
console.log('Called getNumberBtnn');
}
<div>
<input type="number" id="number" min="1" max="1000">
<button id="apply">Apply</button>
</div>
You do not assign the event handler but the result of the function.
As I said in my comment, remove the () from the end of the function you assign.
Also you do not assign anything to x
However I suggest you do this instead:
Use eventListener
Use a function to decide which function to call
Have the list on functions in an object
Actually have different functions
let equation = 0;
const funcs = {
"btn": function(x) {
equation += x; // for example
console.log("btn", equation)
},
"btnn": function(x) {
equation *= x; // for example
console.log("btnn", equation)
}
}
document.getElementById("apply").addEventListener("click", function(e) {
const tgt = e.target;
const func = tgt.dataset.func
tgt.dataset.func = func === "btn" ? "btnn" : "btn"; // toggle the function
funcs[func](+document.getElementById("number").value); // call the chose function with a value
})
<div>
<input type="number" id="number" min="1" max="1000">
<button type="button" data-func="btn" id="apply">Apply</button>
</div>
Remove () from in front of function name while editing onclick property
function getNumberBtn() {
document.getElementById("apply").onclick = getNumberBtnn;
equation = equation + x;
}
function getNumberBtnn() {
document.getElementById("apply").onclick = getNumberBtn;
equation = equation + x;
}

Adding sum of array with pushed input values

I have pushed an input value to an empty array and converted it into a number. I am trying to add up the array and show the sum. But the whole array is shown and no addition has been done. I've included some of the code here but I'll also include the JS fiddle in case I forgot something important. I may be overthinking it as I have been looking at it for sometime.
JS Fiddle: https://jsfiddle.net/nzart/emruz0sb/4/
// HTML
<h1>Sugar Counter:</h1><p id="total">--</p>
<div class="box bot1">
<div class="twogrid mid">
<label for="amount">Amount of Sugar</label>
<input type="text" name="amount" id="amount">
</div>
</div>
//JS
var added = [];
//Get Data
var userInput = function(){
return parseFloat(document.getElementById('amount').value);
}
// Store Data
var newSugar = function(){
return added.push(userInput());
}
//Add total
function total() {
var sum = 0;
for (var i = 0; i < added.length; i++) {
sum += added[i];
}
document.getElementById('total').textContent = added;
}
This line is incorrect inside of function total():
document.getElementById('total').textContent = added;
Change to this:
document.getElementById('total').textContent = sum;
Here is an updated fiddle: https://jsfiddle.net/bqt1mws7/
You are displaying the array variable not the sum variable. Assign the sum variable to #total, not added variable.
document.getElementById('total').textContent = sum;
You need a button to perform the summation to update the total.
The Array.prototype.reduce function is a easy way to total values inside of a list.
values.reduce((runningTotal, currentValue) => runningTotal + currentValue, initialValue)
var valueList = [];
document.getElementById('btn-add').addEventListener('click', onAddClick);
function onAddClick(e) {
var value = getCurrentValue();
if (isNaN(value)) {
alert('Value is not a number!');
return;
}
valueList.push(value);
document.getElementById('total').textContent = getTotal();
}
function getCurrentValue() {
return parseFloat(document.getElementById('amount').value.trim());
}
function getTotal() {
return valueList.reduce((a, b) => a + b, 0); // Sum the values in the list
}
<h1>Sugar Counter:</h1>
<label>Total:</label>
<span id="total">--</span>
<div class="box bot1">
<div class="twogrid mid">
<label for="amount">Amount of Sugar</label>
<input type="text" name="amount" id="amount">
<input type="button" value="Add" id="btn-add" />
</div>
</div>
There is no problem in the addition process. If the array is valid, the total() function will work well. But at the last statement of total() function, you put added variable as output. But it should be the value of sum variable.
function total() {
var sum = 0;
for (var i = 0; i < added.length; i++) {
sum += added[i];
}
document.getElementById('total').textContent = sum;
}

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>

Limiting character in textbox input

please be nice. I'm trying to create a page which sets limit and cut the excess (from the specified limit). Example: Limit is 3. then, I'll input abc if I input d it must say that its limit is reached and the abc will remain. My problem is that it just delete my previous input and make new inputs. Hoping for your great cooperation. Thanks.
<html>
<script type="text/javascript">
function disable_btn_limit(btn_name)
{
/* this function is used to disable and enable buttons and textbox*/
if(btn_name == "btn_limit")
{
document.getElementById("btn_limit").disabled = true;
document.getElementById("ctr_limit_txt").disabled = true;
document.getElementById("btn_edit_limit").disabled = false;
}
if(btn_name == "btn_edit_limit")
{
document.getElementById("btn_limit").disabled = false;
document.getElementById("ctr_limit_txt").disabled = false;
document.getElementById("btn_edit_limit").disabled = true;
}
}
function check_content(txtarea_content)
{
/*This function is used to check the content*/
// initialize an array
var txtArr = new Array();
//array assignment
//.split(delimiter) function of JS is used to separate
//values according to groups; delimiter can be ;,| and etc
txtArr = txtarea_content.split("");
var newcontent = "";
var momo = new Array();
var trimmedcontent = "";
var re = 0;
var etoits;
var etoits2;
//for..in is a looping statement for Arrays in JS. This is similar to foreach in C#
//Syntax: for(index in arr_containter) {}
for(ind_val in txtArr)
{
var bool_check = check_if_Number(txtArr[ind_val])
if(bool_check == true)
{
//DO NOTHING
}
else
{
//trim_content(newcontent);
newcontent += txtArr[ind_val];
momo[ind_val] = txtArr[ind_val];
}
}
var isapa = new Array();
var s;
re = trim_content(newcontent);
for(var x = 0; x < re - 1; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
}
function trim_content(ContentVal)
{
//This function is used to determine length of content
//parseInt(value) is used to change String values to Integer data types.
//Please note that all value coming from diplay are all in String data Type
var limit_char =parseInt(document.getElementById("ctr_limit_txt").value);
var eto;
if(ContentVal.length > (limit_char-1))
{
alert("Length is greater than the value specified above: " +limit_char);
eto = limit_char ;
etoits = document.getElementById("txtarea_content").value;
//document.getElementById("txtarea_content").value = "etoits";
return eto;
//for(var me = 0; me < limit_char; me++)
//{document.getElementById("txtarea_content").value = "";}
}
return 0;
}
function check_if_Number(ContentVal)
{
//This function is used to check if a value is a number or not
//isNaN, case sensitive, JS function used to determine if the values are
//numbers or not. TRUE = not a number, FALSE = number
if(isNaN(ContentVal))
{
return false;
}
else
{ alert("Input characters only!");
return true;
}
}
</script>
<table>
<tr>
<td>
<input type="text" name="ctr_limit_txt" id="ctr_limit_txt"/>
</td>
<td>
<input type="button" name="btn_limit" id="btn_limit" value="Set Limit" onClick="javascript:disable_btn_limit('btn_limit');"/>
</td>
<td>
<input type="button" name="btn_edit_limit" id="btn_edit_limit" value="Edit Limit" disabled="true" onClick="javascript:disable_btn_limit('btn_edit_limit');"/>
</td>
</tr>
<tr>
<td colspan="2">
<textarea name="txtarea_content" id="txtarea_content" onKeyPress="javascript:check_content(this.value);"></textarea>
<br>
*Please note that you cannot include <br>numbers inside the text area
</td>
</tr>
</html>
Try this. If the condition is satisfied return true, otherwise return false.
<html>
<head>
<script type="text/javascript">
function check_content(){
var text = document.getElementById("txtarea_content").value;
if(text.length >= 3){
alert('Length should not be greater than 3');
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<div>
<textarea name="txtarea_content" id="txtarea_content" onkeypress=" return check_content();"></textarea>
</div>
</body>
</html>
Instead of removing the extra character from the text area, you can prevent the character from being written in the first place
function check_content(event) { //PARAMETER is the event NOT the content
txtarea_content = document.getElementById("txtarea_content").value; //Get the content
[...]
re = trim_content(newcontent);
if (re > 0) {
event.preventDefault(); // in case the content exceeds the limit, prevent defaultaction ie write the extra character
}
/*for (var x = 0; x < re - 1; x++) {
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}*/
}
And in the HTML (parameter is the event):
<textarea ... onKeyPress="javascript:check_content(event);"></textarea>
Try replacing with this:
for(var x = 0; x < re - 6; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
Any reason why the maxlength attribute on a text input wouldn't work for so few characters? In your case, you would have:
<input type="text" maxlength="3" />
or if HTML5, you could still use a textarea:
<textarea maxlength="3"> ...
And then just have a label that indicates a three-character limit on any input.

Categories