Would like to be able to add with a "/" or a "," sign as well as the traditional "+" sign. Obviously the "/" sign is used for division, but I would like to change its purpose.
JavaScript
function CalculateIMSUB(form) {
var Atext = form.input_A.value;
var Btext = form.input_B.value;
var val = form.val.value;
var A = eval(Atext);
var B = eval(Btext);
if (isNaN(A)) A = 0;
if (isNaN(B)) B = 0;
var answer = A - B;
form.Answer.value = answer;
form.input_A.value = form.input_A.value.replace(/\+/g, ",");
form.input_B.value = form.input_B.value.replace(/\+/g, ",");
}
function calculateAll() {
var forms = document.getElementsByTagName("form");
for (var i = 0; i < forms.length; i++) {
CalculateIMSUB(forms[i]);
}
}
HTML
<form>
<INPUT TYPE=TEXT NAME="input_A" SIZE=15 />
<INPUT TYPE=TEXT NAME="input_B" SIZE=10 />
<INPUT TYPE="button" VALUE="+" name="SubtractButton" onclick="CalculateIMSUB(this.form)"
/>
<INPUT TYPE=TEXT NAME="Answer" SIZE=12 />
<input type="hidden" name="val" value="1221" />
</form>
Here's my example
Try implementing something like this. No eval, just arrays.
function add( value ) {
return value.split(/[+,\/]/).reduce(function( a,b ) {
return +a + +b;
});
}
console.log( add('1+1+1') ); //=> 3
console.log( add('2,2,2') ); //=> 6
console.log( add('3/3/3') ); //=> 9
Related
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.
I am trying to create four inputs and display all of them after clicking the button. However it returns null. What's wrong with my code?
function addname() {
for (count = 0; count < 5; count++) {
var x = " ";
var inputID = "clientname" + (count + 1);
x = document.getElementById(inputID).value
}
var f = "";
for (var count = 0; count < 5; count++) {
f += x[count];
}
document.write(f)
}
<input type="text" id="clientname1" />
<input type="text" id="clientname2" />
<input type="text" id="clientname3" />
<input type="text" id="clientname4" />
<button onclick="addname()"></button>
Immediate fix: There are 4 inputs, not 5, and stop x from being abused:
function addname() {
var names = [];
for (count = 0; count < 4; count++) {
var inputId = " clientname" + (count + 1);
var name = document.getElementById( inputId ).value;
names.push( name );
}
var f = "";
for (var count = 0; count < 5; count++) {
f += names[count];
}
document.getElementById( 'output' ).textContent = f; // Never use `document.write`!
}
<input type="text" id="clientname1" />
<input type="text" id="clientname2" />
<input type="text" id="clientname3" />
<input type="text" id="clientname4" />
<button onclick="addname()">Concatenate names</button>
<span id="output"></span>
Revision 2: Simplified: Using querySelectorAll with a substring attribute match, and join to concatenate strings:
function concatenateNames() {
const inputs = document.querySelectorAll( 'input[type=text][id^="clientname"]' );
const names = []; // `const` means the variable cannot be reassigned, not that it's immutable.
for( let i = 0; i < inputs.length; i++ )
{
names.push( inputs[i].value );
}
const allNames = names.join( " " );
document.getElementById( 'output' ).textContent = allNames;
}
Revision 3: Simplified further, using Array.from so we can use map with NodeListOf<T>, and adding filter to exclude empty values:
function concatenateNames() {
const inputs = Array.from( document.querySelectorAll( 'input[type=text][id^="clientname"]' ) );
const names = inputs.map( inputEl => inputEl.value ).filter( n => n.length > 0 );
const allNames = names.join( " " );
document.getElementById( 'output' ).textContent = allNames;
}
Revision 4: Simplified further, inlining intermediate variables only used once:
function concatenateNames() {
document.getElementById( 'output' ).textContent =
Array.from(
document.querySelectorAll( 'input[type=text][id^="clientname"]' )
)
.map( inputEl => inputEl.value )
.filter( n => n.length > 0 )
.join( " " );
}
Revision 5: Using nextElementSibling and an inline onclick handler in a single line and shortening identifiers:
<input type="text" id="clientname1" />
<input type="text" id="clientname2" />
<input type="text" id="clientname3" />
<input type="text" id="clientname4" />
<button onclick="this.nextElementSibling.textContent = Array.from( document.querySelectorAll('input[type=text][id^=clientname]') ).map(i => i.value).filter(n => n.length > 0).join(' ')">Concatenate names</button>
<span id="output"></span>
Never do this in production code.
JSFiddle demo: https://jsfiddle.net/3md65awo/
Javascript stops running at the error upon count = 4 trying to get element by id "clientname5"
Either add another text input or change loop to "count = 0; count < 4; count++"
Try this code. I used jquery for this.
function addname() {
for (var count = 1; count < 5; count++) {
var x;
x = $("#clientname" +count).val()
console.log(x)
$("#test").append(x)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="inp" id="clientname1" />
<input type="text" name="inp" id="clientname2" />
<input type="text" name="inp" id="clientname3" />
<input type="text" name="inp" id="clientname4" />
<label id = "test"></label>
<input type="button" onclick="addname()" value="click" />
How do I split a var, which I got from a text input on a "+", "-", "x" and "^"?
JavaScript
function integralinput() {
var a = document.getElementById("input").value;
console.log(a);
var b = a.split("x" + "^" + "+" + "-");
console.log(b);
}
html:
<input id="input" type="text"><label for="function">Funktion</label>
<input type="button" onclick="integralinput()" value="Run">
Use a regex
var b = a.split(/[x^+-]/)
If you want only number you can use like this
function integralinput() {
var a = document.getElementById("input").value;
var b = a.match(/\d+/g).map(Number);
console.log(b);
}
<input value="10+20-3x5^6" id="input" type="text"><label for="function">Funktion</label>
<input type="button" onclick="integralinput()" value="Run">
I am making a program that has an array of numbers and then the user inputs some values in and clicks on verify. the value he enters has to be in order with the array of numbers and if it isn't the user gets an alert message sorry.
The value inside the first input bar decides from which number of the array should the comparison should start. For example, if the array holds numbers like {2,4,6,8,10} and the user enters 6 in the first input bar and then he enters 8 and 10 in the next two bars, he should get the result "678"
If he doesn't get the first number right lets say he enters 3, and since 3 isn't in the array, then it doesn't matter what he enters in the other input bars, he would get the result "Sorry".
Similarly, if the user types 4 in the first input bar but then then in the second bar he types 8, he should still get the result "Sorry" since the order of the array is {4,6,8} not {4,8}.
I made a program but whenever I click on the verify button, nothing happens.
Here is my codes. and here is also the result I am getting:
https://jsfiddle.net/53j19rpt/
<html>
<head>
</head>
<script type="text/javascript">
var arr = [];
var t;
var num = 2;
var x = [];
for (var x = 0; x < 4; x++) {
document.getElementById("one" + x);
}
function go() {
for (var t = 0; t < 4; k++) {
x[t] = num * (t + 1);
}
for (var k = 0; k < 4; k++) {
if (document.getElementById("one0").value >= x[k])
if (document.getElementById("one" + k).value == x[k])
document.write(document.getElementById("one" + k).value);
else
document.write("Sorry");
}
}
</script>
<body>
<input id="one0" type="text">
<input id="one1" type="text">
<input id="one2" type="text">
<input id="one3" type="text">
<input type="button" id="verifyBtn" value="verify" onclick="go()">
</body>
</html>
Version 1 - all 4 have to be correct in order
var x = [],num=2;
// I assume you will want to change this to random later
for (var i = 0; i < 4; i++) {
x[i] = num * (i + 1);
}
console.log(x);
function go() {
var found=0;
for (var i = 0; i < 4; i++) {
if (document.getElementById("one" + i).value == x[i]) {
found++;
}
}
document.getElementById("result").innerHTML = found==x.length?x:"Sorry";
}
<input id="one0" type="text" value="" />
<input id="one1" type="text" value="" />
<input id="one2" type="text" value="" />
<input id="one3" type="text" value="" />
<input type="button" id="verifyBtn" value="verify" onclick="go()" />
<span id="result"></span>
Version 2 Error if anything entered is wrong
var x = [],
num = 2;
// I assume you will want to change this to random later
for (var i = 0; i < 4; i++) {
x[i] = ""+num * (i + 1); // make string
}
console.log(x);
window.onload = function() {
var field = document.querySelectorAll(".entry");
for (var i = 0; i < field.length; i++) {
field[i].onkeyup = function() {
document.getElementById("result").innerHTML = (x.indexOf(this.value) == -1)?"Sorry":this.value;
}
}
}
function go() {
var field = document.querySelectorAll(".entry"),
error = false,
res = "";
for (var i = 0; i < field.length; i++) {
res += field[i].value; // string concatenation
}
document.getElementById("result").innerHTML = (res == x.join("")) ? res : "Sorry";
}
<input class="entry" id="one0" type="text" value="" />
<input class="entry" id="one1" type="text" value="" />
<input class="entry" id="one2" type="text" value="" />
<input class="entry" id="one3" type="text" value="" />
<input type="button" id="verifyBtn" value="verify" onclick="go()" /><br/>
<span id="result">test</span>
Version 3 - any 1, 2, 3 or 4 entries are deemed correct if they are subpart of array, e.g. 46 is ok and so is 68 but not 26
var x = [],
num = 2;
// I assume you will want to change this to random later
for (var i = 0; i < 4; i++) {
x[i] = ""+num * (i + 1); // make string
}
console.log(x);
window.onload = function() {
var field = document.querySelectorAll(".entry");
for (var i = 0; i < field.length; i++) {
field[i].onkeyup = function() {
document.getElementById("result").innerHTML = (x.indexOf(this.value) == -1)?"Sorry":this.value;
}
}
}
function go() {
var field = document.querySelectorAll(".entry"),
error = false,
res = [];
for (var i = 0; i < field.length; i++) {
if (x.indexOf(field[i].value) !=-1) res.push(field[i].value);
}
document.getElementById("result").innerHTML = (x.join(".").indexOf(res.join("."))!=-1) ? res : "Sorry";
}
<input class="entry" id="one0" type="text" value="" />
<input class="entry" id="one1" type="text" value="" />
<input class="entry" id="one2" type="text" value="" />
<input class="entry" id="one3" type="text" value="" />
<input type="button" id="verifyBtn" value="verify" onclick="go()" /><br/>
<span id="result">test</span>
If I understand your question well this should work:
<html>
<head>
</head>
<body>
<input id="one0" type="text" value="">
<input id="one1" type="text" value="">
<input id="one2" type="text" value="">
<input id="one3" type="text" value="">
<input type="button" id="verifyBtn" value="verify" onclick="go()">
<script type="text/javascript">
function go() {
var arrinputs = [];
var arr = [2, 4, 10, 12];
for (var x = 0; x < 4; x++) {
var tmp = parseInt(document.getElementById("one" + x).value)
if (!isNaN(tmp))
arrinputs.push(tmp);
}
var a = "-" + arrinputs.join('-') + "-";
var b = "-" + arr.join('-') + "-";
if (b.indexOf(a) != -1) {
alert("Ok!");
} else {
alert("Sorry!");
}
}
</script>
</body>
</html>
Test 1 (check array 2, 4, 6, 8)
Returns: Corrent
Test 2 (check array 2, 4, 6, 8)
Returns: Corrent
Test 3 (check array 2, 4, 6, 8)
Returns: Sorry
Test 4 (check array 2, 4, 10, 12)
Returns: Corrent
Test 5 (check array 2, 4, 10, 12)
Returns: Sorry
Test 6 (check array 2, 4, 10, 12)
Returns: Sorry
How can I use the value from a function in an if statement. I have a form where I was using return false in my script but I need changed it to preventDefault.
<form id="percentageBiz" method="post">
<input type="text" id="sum1">
<input type="text" id="sum2">
<input type="submit" onclick="return" value="Get Total">
</form>
<div id="display"></div>
<script>
$('#percentageBiz').submit(function(e) {
var a = document.forms["percentageBiz"]["sum1"].value;
var b = document.forms["percentageBiz"]["sum2"].value;
var display=document.getElementById("display")
display.innerHTML=parseInt(a,10)+parseInt(b,10);
e.preventDefault();
});
if (display < 100) {
$("#display").addClass("notequal");
}
</script>
$('#percentageBiz').submit(function(e) {
e.preventDefault();
var $display = $("#display", this);
var a = $("#sum1", this).val();
var b = $("#sum2", this).val();
var sum = +a + +b;
$display.text( sum );
if ( sum < 100 ) {
$display.addClass("notequal");
}
});