how to store elements in array but by trucating leading zeros - javascript

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>

Related

adding new value to variable

I have a question I have simple JavaScript that do some basic stuff to a number from input. I have a question how can I make variable that will always track the new input value for example if I enter 123 and click on some of the following buttons I get the result, but if I now enter new number for example 54321 and click again on some of the buttons I start from the previous value. How can I make my variable change every time a new value is entered or changed ? Here is my code:
var number = document.getElementById("number");
var numberValue = number.value;
console.log(numberValue);
function plus() {
number.value = ++numberValue;
}
function minus() {
number.value = --numberValue;
}
function flip() {
var temp = numberValue;
var cifra, prevrten = 0;
while (temp > 0) {
cifra = temp % 10;
prevrten = (prevrten * 10) + cifra;
temp = temp / 10 | 0;
}
number.value = prevrten;
}
window.onload = function() {
number.value = "";
}
<div>
<input type="text" id="number" id="output" onload="restart();">
<input type="button" value="<" onclick="minus();">
<input type="button" value=">" onclick="plus();">
<input type="button" value="FLIP" onclick="flip();">
<input type="button" value="STORE" onclick="store();">
<input type="button" value="CHECK" onclick="check();">
</div>
I suggest you use a type="number" and case the value to number - her I use the unary plus to do so
You will need to read the value in all functions
let numberValue = 0;
function store() {}
function check() {}
function plus() {
numberValue = +number.value;
number.value = ++numberValue;
}
function minus() {
numberValue = +number.value;
number.value = --numberValue;
}
function flip() {
let numberValue = +number.value;
var cifra, prevrten = 0;
while (numberValue > 0) {
cifra = numberValue % 10;
prevrten = (prevrten * 10) + cifra;
numberValue = numberValue / 10 | 0;
}
number.value = prevrten;
}
window.addEventListener("load", function() {
let number = document.getElementById("number");
number.value = 0;
})
<div>
<input type="number" id="number" id="output" onload="restart();">
<input type="button" value="<" onclick="minus();">
<input type="button" value=">" onclick="plus();">
<input type="button" value="FLIP" onclick="flip();">
<input type="button" value="STORE" onclick="store();">
<input type="button" value="CHECK" onclick="check();">
</div>
Try using onChange="".
<input type="text" id="number" id="output" onload="restart();" onChange="updateVal();">
function updateVal() {
numberValue = number.value;
}
I would suggest, for something like this, it would be much easier to use React JS or another framework with state.

trying to link checkbox list with multiple functions using HTML & JAVASCRIPT

my code calculates the AVG or MAX of an input set of numbers, I want the user to check on a checkbox list that contains AVG and MAX for desired output but I couldn't figure out doing it.
if I put an input of "2,4" without check listing the output is both AVG and MAX which is 3 4, I tried to checklist for only AVG or MAX outcome but it didn't work.
I have checked both function calculateAVG() & calculateMAX() and they produce correct output
function proccesFloat(flt) {
var splitFloat = flt.split(",");
for (x in splitFloat) {
splitFloat[x] = parseFloat(splitFloat[x]);
}
return splitFloat;
}
function calculateAVG(setNum) {
let total = 0;
var numInput = document.getElementById("setNum").value;
var result = 0;
var avg = proccesFloat(numInput);
for (let i = 0; i < avg.length; i++) {
total += avg[i];
}
result = total / avg.length;
document.getElementById('outputAVG').innerHTML = result;
}
function calculateMAX(setNum) {
var numInput = document.getElementById("setNum").value;
var numarry = proccesFloat(numInput);
var max = 0;
for (let i = 0; i < numarry.length; i++) {
if (numarry[i] > max) {
max = numarry[i];
}
}
document.getElementById('outputMAX').innerHTML = max;
}
function calculate() {
var checkBox = document.getElementsByTagName("check");
if (checkBox[0].checked) {
calculateAVG(document.getElementById("setNum"));
}
if (checkBox[0].checked) {
calculateMAX(document.getElementById("setNum"));
} {
alert('please choose formula')
return false;
}
}
<header>
<input type="Numbers" id="setNum" placeholder="Enter Set of Numbers">
<br>
<button onclick="calculate()" id="btn1">calculate</button>
<output id="outputAVG"></output>
<output id="outputMAX"></output>
<form method="post">
<fieldset>
<legend>Formula To Calculate?</legend>
<input type="checkbox" id="avg" name="check" onclick="calculate()">AVG<br>
<input type="checkbox" id="max" name="check" onclick="calculate()">MAX<br>
<br>
</fieldset>
</form>
</header>
Count the checked and then look at the IDs.
I also suggest you wrap in a form and use the submit event
I made a few more changes to simplify the code
Let the functions do one thing and use the event to bring them together
const proccesFloat = flt => flt.split(",").map(fl => +fl); // cast to float
const calculateAVG = setNum => {
const arr = proccesFloat(setNum);
const total = arr.reduce((a, b) => a + b)
return total / arr.length;
}
const calculateMAX = setNum => Math.max(...proccesFloat(setNum));
document.getElementById("calcForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission
const chks = document.querySelectorAll("[name=check]:checked")
if (chks.length === 0) {
alert('please choose formula')
return
}
if (document.getElementById("avg").checked) {
document.getElementById('outputAVG').innerHTML = calculateAVG(document.getElementById("setNum").value);
}
if (document.getElementById("max").checked) {
document.getElementById('outputMAX').innerHTML = calculateMAX(document.getElementById("setNum").value);
}
})
<header>
<form id="calcForm">
<input type="Numbers" id="setNum" placeholder="Enter Set of Numbers">
<br>
<button type="submit">calculate</button>
<output id="outputAVG"></output>
<output id="outputMAX"></output>
<fieldset>
<legend>Formula To Calculate?</legend>
<input type="checkbox" id="avg" name="check">AVG<br>
<input type="checkbox" id="max" name="check">MAX<br>
<br>
</fieldset>
</form>
</header>

Why is my character counter not excluding spaces?

I am making a character counter with HTML, CSS, JS. I got the counter working, but I have a checkbox that should get the length of the input without the spaces, but it is not working. Please check my code and tell me what's wrong.
function char_count(str, letter) {
var letter_Count = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == letter) {
letter_Count += 1;
}
}
return letter_Count;
}
function countChars(obj) {
var length = obj.value.length;
var output = document.getElementById("chars");
var dis = document.getElementById("removeSpace");
if (dis.checked) {
var spaces = char_count(obj, " ");
length = length - spaces;
output.innerHTML = length + ' characters';
} else {
output.innerHTML = length + ' characters';
}
}
<h1> Character Counter </h1>
<textarea id="input" onkeyup="countChars(this)" placeholder="Enter your text here..." autofocus></textarea>
<input type="checkbox" id="removeSpace">
<label for="removeSpace" onclick="countChars(document.getElementById('input'))">Don't Include Spaces</label>
<span id="chars">0 Characters</span>
You could make the code more simpler. Moreover, you have placed the checkbox outside the label that has onclick="countChars(document.getElementById('input'))", that's why the condition dis.checked in js does not find the checkbox as checked. Place the checkbox inside the label.
The whole simplified code would be like this,
<h1> Character Counter </h1>
<textarea id="input" onkeyup="countChars(this)" placeholder="Enter your text here..." autofocus></textarea>
<label for="removeSpace" onclick="countChars(document.getElementById('input'))">
<input type="checkbox" id="removeSpace">
Don't Include Spaces</label>
<span id="chars">0 Characters</span>
<script>
function countChars(obj) {
var length = obj.value.length;
var output = document.getElementById("chars");
var dis = document.getElementById("removeSpace");
if (dis.checked) {
length = obj.value.replace(/\s/g, '').length
}
output.innerHTML = length + ' characters';
}
</script>

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.

How to remove characters in a field javascript

I tried using the following code to format a text field value from (N50,000.00 NGN) to (50000) but the result instead of producing 50000 is producing 5000000.
Can someone please help?
<script type="text/javascript" language="javascript">
function doWork() {
var amount = document.getElementsByName('amount');
var str = amount[0].value;
var temp = '';
for (i = 0; i < str.length; i++) {
if (!isNaN(str[i]))
temp += str[i];
}
amount[0].value = temp;
}
</script>
<input type="text" name="amount" value="N50,000.00 NGN" />
<input type="button" value="submit" onclick="doWork();">
The simplest method to get what you want might be to just add another condition in your for loop:
if (str[i] === '.')
break;
Let's take a look at the value you are trying to format.
In N50,000.00 NGN all digits are not NaN. So your result is 5000000 (50 000 00). The solution is to stop at dot symbol, e.g.
function doWork() {
var amount = document.getElementsByName('amount');
var str = amount[0].value;
var temp = '';
for (i = 0; i < str.length; i++) {
if (str[i] === '.') break; // there it is
if (!isNaN(str[i]))
temp += str[i];
}
amount[0].value = temp;
}
Here's one way to do it with a regex. Note, that if the user has multiple decimal points in the input field it may act oddly.
<script type="text/javascript" language="javascript">
function doWork() {
var amount = document.getElementsByName('amount');
amount[0].value = amount[0].value.replace(/[^0-9.]/g, "");
amount[0].value = amount[0].value.replace(/[.][0-9]*/g, "");
}
</script>
<input type="text" name="amount" value="N50,000.00 NGN" />
<input type="button" value="submit" onclick="doWork();">
The first line removes all characters except numbers and decimal points.
The second, removes all decimal points and any numbers to the right of them.
Using parseInt and toFixed may be better, though:
<script type="text/javascript" language="javascript">
function doWork() {
var amount = document.getElementsByName('amount');
amount[0].value = parseInt(amount[0].value.replace(/[^0-9.]/g, "")).toFixed(0);
}
</script>
<input type="text" name="amount" value="N50,000.00 NGN" />
<input type="button" value="submit" onclick="doWork();">
You're skipping over the decimal. Use:
if (!isNaN(str[i]) || str[i]=='.')

Categories