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
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'm trying to make a code where you input a number n and the code returns you the number in the Fibonacci sequence.
Example:
When inputting n = 1 the code returns 1, and when you input n = 2 the code returns 1, and when you input n = 3 the code returns 2, and so on.
I'm quite a beginner with javascript so I don't know exactly how to do this.
<html>
<body>
<script type="text/javascript">
function fibonacci(){
var a, b, n, result;
a = 0;
b = 1;
for (var i = 0; i <= n; i++)
{
if(n == 1)
{
return 1;
}
if(n == 0)
{
return 0;
}
result = a + b;
a = b;
b = result;
}
document.getElementById("result").value = result;
}
</script>
<form>
<input id="n" type="number" placeholder="N">
<input id="result" type="number" placeholder="Result" readonly="">
<input id="calculate" type="button" value="Calculate" onclick="fibonacci()">
<input type="reset" value="Clear">
</form>
</body>
</html>
You didn't initialized n, right?
Add this line before for loop.
n = document.getElementById("n").value
Check your browser console for errors, it shows this kind of errors correctly..
You should initialize n.
Then remove n==0 and n==1 from for loop block.
Update your code following,
<html>
<body>
<script type="text/javascript">
function fibonacci(){
var n = document.getElementById("n").value;
var result;
var a = 0;
var b = 1;
if(n == 0 || n == 1)
{
result = n;
}
else{
for (var i = 2; i <= n; i++)
{
result = a + b;
a = b;
b = result;
}
}
document.getElementById("result").value = result;
}
</script>
<form>
<input id="n" type="number" placeholder="N">
<input id="result" type="number" placeholder="Result" readonly="">
<input id="calculate" type="button" value="Calculate" onclick="fibonacci()">
<input type="reset" value="Clear">
</form>
</body>
</html>
I am new to javascript and I am trying to make a lottery game where I generate 8 random hexadecimal numbers like 15 4A FF 45 77 C3 EE 7E and introduce my numbers.I want to find how many numbers I guessed. I take the values from input and put them into an array and insert space between numbers, then splitting the result.The same with the numbers generated but I can't figure out I don't get the correct result.
<section id="section2">
<h2>Internet Loto</h2>
<button onclick="genHexString();">Genereaza numere</button>
<br />
<button onclick="tryAgain()" ;>Incearca din nou</button>
<p id="loto"></p>
<p class="numere">
<label for="nr1">Nr1:</label>
<input pattern="[A-Z0-9]{2}" id="nr1">
<label for="nr2">Nr2:</label>
<input pattern="[A-Z0-9]{2}" id="nr2">
<label for="nr3">Nr3:</label>
<input pattern="[A-Z0-9]{2}" id="nr3">
<label for="nr4">Nr4:</label>
<input pattern="[A-Z0-9]{2}" id="nr4">
<label for="nr5">Nr5:</label>
<input pattern="[A-Z0-9]{2}" id="nr5">
<label for="nr6">Nr6:</label>
<input pattern="[A-Z0-9]{2}" id="nr6">
<label for="nr7">Nr7:</label>
<input pattern="[A-Z0-9]{2}" id="nr7">
<label for="nr8">Nr8:</label>
<input pattern="[A-Z0-9]{2}" id="nr8">
</p>
</section>
function genHexString() {
var output = "";
for (let i = 0; i < 16; ++i) {
output += (Math.floor(Math.random() * 16)).toString(16).toUpperCase();
document.getElementById("loto").innerHTML += ' ';
if (i % 2 != 0 && i < 15) {
output += ' '; // space for display each number as pair of 2 characters
}
}
var res = output.split(" ");
document.getElementById("loto").innerHTML = "Winning numbers: " + output;
var input = "";
for (let i = 1; i < 9; i++) {
var x = "nr" + i;
input += document.getElementById(x).value + ' ';
}
var res2 = input.split(" ");
document.getElementById("loto").innerHTML += "<br/>Your numbers: " + res2;
var count = 0;
var i, j;
for (i = 0; i < output.length; i++) {
for (j = 0; j < input.length; j++) {
if (res[i] == res2[j]) {
count += 1;
}
}
}
document.getElementById("loto").innerHTML += "<br/>Numere ghicite: " + count;
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
includes function can come in hand.
Try this
function genHexString() {
var output = "";
for (let i = 0; i < 16; ++i) {
output += (Math.floor(Math.random() * 16)).toString(16).toUpperCase();
document.getElementById("loto").innerHTML += ' ';
if (i % 2 != 0 && i < 15) {
output += ' '; // space for display each number as pair of 2 characters
}
}
document.getElementById("loto").innerHTML = "Winning numbers: " + output;
var count = 0;
var input = "";
console.clear();
for (let i = 1; i <= 8; i++) {
var x = `nr${i}`;
let value=document.getElementById(x).value;
if(output.includes(value) && value)
count++;
input += value + ' ';
}
document.getElementById("loto").innerHTML += "<br/>Your numbers: " + input;
document.getElementById("loto").innerHTML += "<br/>Numere ghicite: " + count;
}
label{
margin-left:10px;
}
input{
margin-top:5px;
margin-left:30px;
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
<section id="section2">
<h2>Internet Loto</h2>
<button onclick="genHexString();">Genereaza numere</button>
<br />
<button onclick="tryAgain()" ;>Incearca din nou</button>
<p id="loto"></p>
<p class="numere">
<label for="nr1">Nr1:</label>
<input pattern="[A-Z0-9]{2}" id="nr1">
<label for="nr2">Nr2:</label>
<input pattern="[A-Z0-9]{2}" id="nr2">
<label for="nr3">Nr3:</label>
<input pattern="[A-Z0-9]{2}" id="nr3">
<label for="nr4">Nr4:</label>
<input pattern="[A-Z0-9]{2}" id="nr4">
<label for="nr5">Nr5:</label>
<input pattern="[A-Z0-9]{2}" id="nr5">
<label for="nr6">Nr6:</label>
<input pattern="[A-Z0-9]{2}" id="nr6">
<label for="nr7">Nr7:</label>
<input pattern="[A-Z0-9]{2}" id="nr7">
<label for="nr8">Nr8:</label>
<input pattern="[A-Z0-9]{2}" id="nr8">
</p>
</section>
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" />
I created two input fields where they should substract from each other keeping a max value at 100.
Currently it substracted value is shown in the second value. I want it to be interchangeable. Irrespective of whether I put in first or second input field, the answer shows in the other.
Could someone help?
function updateDue() {
var total = parseInt(document.getElementById("totalval").value);
var val2 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
var val1 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val1) { val1 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val1;
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue()">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue()">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue()">
</div>
The simple way to achieve this would be to group the inputs by class and attach a single event handler to them. Then you can take the entered value from 100, and set the result to the field which was not interacted with by the user. To do that in jQuery is trivial:
$('.updatedue').on('input', function() {
var total = parseInt($('#totalval').val(), 10) || 0;
var subtracted = total - (parseInt(this.value, 10) || 0);
$('.updatedue').not(this).val(subtracted);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="totalval" name="totalval" value="100" />
<div>
Enter Value:
<input type="text" name="inideposit" class="updatedue form-control" id="inideposit" />
</div>
<div>
Subtracted:
<input type="text" name="remainingval" class="updatedue form-control" id="remainingval" />
</div>
You can easily validate this so that outputs < 0 and > 100 can be discounted, if required.
Edit your code as below
function updateDue(box) {
var total = parseInt(document.getElementById("totalval").value);
if(box == 1){
var val = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val;
}else if(box == 2){
var val = parseInt(document.getElementById("remainingval").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("inideposit");
ansD.value = total - val;
}
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue(0)">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue(1)">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue(2)">
</div>