for-loop doesn't function properly - javascript

Can anyone help me on my issue, it seems that my loop doesn't work. I created a random number guessing game, and I wanted to have only 5 tries. And once it hits the 5th try, it will display a message. But it seems that I was able to do it countless time.
function RandomNumber()
{
//get value from random number textbox
var lol=document.getElementById("guess").value;
//get new value from user
var ass=document.getElementById("textbox").value;
var maxtries=5;
for(var i=0;i<=maxtries;i++)
{
if(ass == lol)//if user guess correctly
{
document.getElementById("correct").innerHTML="Correct"
}
else if(ass!=lol)//if user guess wrongly
{
document.getElementById("correct").innerHTML="Not correct"
}
else if (i==maxtries)
{
document.getElementById("correct").innerHTML="No more tries"
}
}
}
This is my <form> codes
<td style="text-align:center">
Lowest number:
<input id="digit" type="text" name="lowestnumber" onchange="validate()"><br/>
<br/><span id="numbers"></span>
</td>
</tr>
<tr>
<td style="text-align:center">
Highest number:
<input id="digit1" type="text" name="highestnumber" onchange="validate()"><br/>
<br/><span id="numbers1"></span>
</td>
</tr>
<tr>
<td style="text-align:center">
<br/><input id="rand" type="submit" value="submit" onclick="Random()" disabled><br/>
<input id="guess" type="text" value="Random Number Generator">
</td>
</tr>
<tr>
<td style="text-align:center">
<br/>Enter your number<br/>
<input id="textbox" type="text"><br/>
<input id="guessing" type="button" value="Random" onclick="RandomNumber()"><br/>
<br/><span id="correct"></span>
</td>

There's a couple problems here. The first and biggest (maybe) is that your loop counts down right away and doesn't give the guesser a chance to make another guess. The second problem is that the 3rd if statement that checks for the number of guesses can never be reached. I have refactored this check to the beginning on the function.
You should call RandomNumber when the user submits a new guess
You can fix this like:
function RandomNumber()
{
if (!this.guesses) {
this.guesses = 1;
} else {
this.guesses++;
if (this.guesses > 5) {
document.getElementById("correct").innerHTML="No more tries";
return; // max guesses exceeded
}
}
//get value from random number textbox
var lol=document.getElementById("guess").value;
//get new value from user
var ass=document.getElementById("textbox").value;
if(ass == lol)//if user guess correctly
{
document.getElementById("correct").innerHTML="Correct"
}
else if(ass!=lol)//if user guess wrongly
{
document.getElementById("correct").innerHTML="Not correct"
}
}

Right now, your loop runs 6 times in a row. What you want is no loop at all, but a simple counter that can keep track of how many guesses have been made and when the count reaches the max, the guessing is over.
Other Notes:
You seem to have an excessive amount of input elements and since
this is just a game and you are not actually submitting the data
anywhere, you shouldn't be using submit buttons and adding name
attributes to the form fields.
You should not be using tables for page layout - - that's the job of
CSS.
Don't use .innerHTML when you aren't working with strings that
contain HTML as .innerHTML has security and performance
implications. Use .textContent instead.
Don't use inline HTML event attributes. Do you JavaScript separately
from your HTML.
Don't use self-terminating syntax.
const checkAnswer=document.getElementById("guessing");
const d1= document.getElementById("digit1");
const d2= document.getElementById("digit2");
const guess = document.getElementById("guess");
const rand = document.getElementById("rand");
const result = document.getElementById("correct");
const maxtries=5;
let count = 1;
let answer = null;
d2.addEventListener("blur", function(){
rand.removeAttribute("disabled");
});
rand.addEventListener("click", function(){
console.log(d1.value, d2.value);
answer = Math.floor(Math.random() * (d2.value - d1.value + 1) + d1.value);;
console.log(answer);
});
checkAnswer.addEventListener("click", randomNumber)
function randomNumber() {
if(count < maxtries){
if(guess.value == answer){
result.textContent="Correct";
} else {
result.textContent="Guess " + count + " Not correct";
}
count++; // Increase the counter
} else {
result.textContent="No more tries";
}
}
<div>
Lowest number: <input id="digit1" type="text">
<br><span id="numbers"></span>
</div>
<div>
Highest number: <input id="digit2" type="text">
<br><span id="numbers1"></span>
</div>
<div>
<input id="rand" type="button" value="Generate Random" disabled><br>
</div>
<div>
Enter your number<br>
<input id="guess" type="text"><br>
<input id="guessing" type="button" value="Check Answer"><br>
<span id="correct"></span>
</div>

Related

Javascript field.setCustomValidity() doesn't set field to valid

I have an HTML form and using Javascript to validate the form. However, when I use setCustomValidity(), it doesn't seem to work properly. I have to click on the submit button twice to mark the field as invalid, and then when the correct input is entered, the field is not marked as valid again, i.e. the error message keeps repeating.
Here's my HTML:
<form id="data_form" onsubmit="event.preventDefault(); return validateForm();">
<table>
<tr>
<td colspan="2" class="right_align">
<label for="supplier_ref"> Supplier Reference Number: </label>
</td>
<td colspan="2">
<input id="supplier_ref" name="supplier_ref" type="number" required>
</td>
</tr>
<!-- more rows -->
<button id="generate" name="generate" type="submit" onclick=""> Generate Barcode </button>
</table>
</form>
Javascript:
function validateForm() {
var form = document.forms["data_form"];
var emptymsg = "Field must be filled out.";
var supplier_ref = form.elements["supplier_ref"];
var supplier_ref_value = supplier_ref.value.toString();
if (supplier_ref_value == "") {
supplier_ref.setCustomValidity(emptymsg);
return false;
}
if (supplier_ref_value.length != 9){
supplier_ref.setCustomValidity("Number has to be 9 digits long.");
return false;
} else {
supplier_ref.setCustomValidity("");
}
return true;
}
When the length of the Supplier Reference is less than 9 digits, the error message appears, but when I enter the correct length, I still get the same error.
I would appreciate any help.
Thanks in advance
Nvm it only works with addEventListener

I can't find a way to get input to be used in the equation and then display the results in html

My problem is that I can't find a way to get input in the HTML textbox and then use it in the equation I have.
I have a basic investment calculator to see how much you would profit after a set amount of time, given the return on your investment per month and the initial investment. The program returns your balance each month given that you have re-invested all of your profits from last month.
My program works when I replace the values of the variables with the window.prompt() function but that seems inconvenient so I want to make use of the textboxes as input methods for the equation variables.
this is my code so far:
<form style="padding: 30px">
<input type="number" id="holdingtime" placeholder=" hold on time" />
<input type="number" id="initialinvestment" placeholder="initial investment" />
<input type="number" id="monthlyreturn" placeholder="monthly return" />
<input type="button">
<br/>
</form>
<div class="dprogramitself" style="padding: 35px; padding-top: 1, font-size: 20px">
<script>
let holdtime = 201;
let initialinvestment = 50000;
let monthlyreturn = 0.15;
document.eval("<li>", initialinvestment, "<br><hr>");
for (let i = 0; i < holdtime; i++) {
initialinvestment = initialinvestment + initialinvestment * monthlyreturn;
document.write("<li>", initialinvestment, "<br><hr>");
}
</script>
</div>
sorry about the cheesy names I just try to be descriptive. Feel free to ask questions as I'm stuck and any help would be appreciated. I'm sure this is simple stuff but I just haven't been able to solve this.
You need to have an event listener to tell JavaScript 'hey, when this button is pressed, run this code'. With a button with id action-button you can add an event listener to it and get the values of your inputs when the button is clicked. You can then run your logic and show it.
document.getElementById("action-button").addEventListener("click", () => {
const holdtime = document.getElementById("holdingtime").value;
});
Docs: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener , https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
You need some eventListeners
Here I delegate from the form and use the change event of any of the fields. When all fields are filled in, I run the calculation
window.addEventListener("load", function() { // when page has loaded
document.getElementById("calcForm").addEventListener("change", function() { // anything changed
let holdtime = +document.getElementById("holdingtime").value; // use unary plus to convert to number
let initialinvestment = +document.getElementById("initialinvestment").value;
let monthlyreturn = +document.getElementById("monthlyreturn").value;
let html = [];
if (holdtime > 0 && initialinvestment > 0 && monthlyreturn > 0) {
for (let i = 0; i <= holdtime; i++) {
html.push(`<li>${initialinvestment.toFixed(0)}<hr></li>`);
initialinvestment += initialinvestment * monthlyreturn;
}
}
document.querySelector(".dprogramitself").innerHTML = html.join("");
});
});
ul {
list-style: none;
}
<form style="padding: 30px" id="calcForm">
<input type="number" id="holdingtime" placeholder=" hold on time" />
<input type="number" id="initialinvestment" placeholder="initial investment" />
<input type="number" id="monthlyreturn" placeholder="monthly return" />
</form>
<ul class="dprogramitself" style="padding: 35px; padding-top: 1, font-size: 20px">
</ul>

I want to create a dynamic table that features data entered by a user when the user hits submit/save (novice programmer)

I am very new to coding in general, and thought the best way to learn would be to make an app of some kind, and went with a simple one. The premise is that if an employee has lost their work pass/badge, and need a temporary one for the day, the receptionist/security can input the employees information along with their assigned badge number into a form. From this form, it is automatically inputted into a table. Within this table, there'll be a checkbox to validate the return of the pass at the end of the day.
I have two problems: the first is I cannot get the data for anything except the employees name and date of birth (so contact numbers/addresses etc. aren't showing), to show when I hit save. The second is I must have hit a wrong key somewhere as now NONE of the data (name and dob included) are showing when I hit save. I have looked over my code several times, however, as I said I am very new to all this (this being my first project), and I'm not sure what I'm supposed to be looking for.
If you guys could offer some guidance, I'd be extremely grateful.
PS. The colours are as they are so I can easily see what I'm changing when playing with the css - the final version will look much better (I hope!). My apologies again for the poor standard of coding: I'm sure it's riddled with obvious signs of an absolute beginner...
This is my HTML file:
<html>
<head>
<title>
My Document
</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="default.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body onload="doShowAll()">
<h1>Pass Manager</h1>
<div id="form" name="input" title="Input Form">
<form >
Name: <input type="text" name="name" />
</br>
Date of Birth: <input type="date" name="dob" />
House Number: <input type="number" name="house_number" />
Postcode: <input type="text" name="postcode" />
Contact Number: <input type="number" name="contact_number" />
Email: <input type="email" name="email" />
</br>
Pass number: <input type="number" name="pass_number" />
</form>
</div>
<form name=Information>
<div id="PlayArea">
<table>
<tr>
<td><b>Name:</b> <input type="text" name="name"></td>
<td><b>Date of Birth:</b> <input type="text" name="dob"></td>
<td><b>House Number:</b> <input type="text" name="houseNumber"></td>
<td><b>Postcode:</b> <input type="text" name="postcode"></td>
<td><b>Contact Number:</b> <input type="number" name="contactNumber"></td>
<td><b>Email:</b> <input type="email" name="email" /></td>
<td><b>Pass Number:</b> <input type="number" name="passNumber"></td>
</tr>
<tr>
<td>
<input type=button value="Save" onclick="SaveItem()">
<input type=button value="Modify" onclick="ModifyItem()">
<input type=button value="Remove" onclick="RemoveItem()">
</td>
</tr>
</table>
</div>
<div id="items_table">
<h2>Loaned Badges</h2>
<table id=list></table>
<p>
<label><input type=button value="Clear" onclick="ClearAll()">
<i>* Removes all items</i></label>
</p>
</div>
</form>
</body>
</html>
And this is my JavaScript file:
function SaveItem() {
var name = document.forms.Information.name.value;
var data = document.forms.Information.data.value;
localStorage.setItem(name, data);
doShowAll();
}
function ModifyItem() {
var name = document.forms.Information.name.value;
document.forms.Information.data.value = localStorage.getItem(name);
doShowAll();
}
function RemoveItem() {
var name = document.forms.Information.name.value;
document.forms.Information.data.value = localStorage.removeItem(name);
doShowAll();
}
function ClearAll() {
localStorage.clear();
doShowAll();
}
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
return true;
}
else {
return false;
}
}
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var list = "<tr><th>Name</th><th>Date of Birth</th><th>House Number</th><th>Postcode</th><th>Contact Number</th><th>Email</th><th>Pass Number</th></tr>\n";
var i = 0;
for (i = 0; i <= localStorage.length - 1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
if (list == "<tr><th>Name</th><th>Date of Birth</th><th>House Number</th><th>Postcode</th><th>Contact Number</th><th>Email</th><th>Pass Number</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot store user preferences as your browser do not support local storage');
}
}
for (i = 0; i <= localStorage.length - 1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
return true;
} else {
return false;
}
}
You have two forms on your page. The two forms look to be similar (not sure why). The first one doesn't have a name, so your code won't be able to access it.
I would recommend that you look at some kind of templating system (like Angular).
What you are doing uses plain old javascript, which isn't wrong, but the way you are dynamically creating javascript is very much a deprecated technique because there are many better ways to do it now. You might as well learn good techniques in a modern framework, because you will need them sooner or later.
The issue you're having is in SaveItem(). Data isn't a field in Information. I've changed it to dob and is appears to work
function SaveItem() {
var name = document.forms.Information.name.value;
// data isn't a member of the Information form.
// var data = document.forms.Information.data.value;
var data = document.forms.Information.dob.value;
localStorage.setItem(name, data);
doShowAll();
}
It's useful if you can show a working example of your code. I've thrown your code into codepen here if you want to see. Codepen example

Incrementing multiple items on click

This is my first time using JavaScript, and I'm having a hard time integrating HTML, CSS, and JavaScript. I've written (with the help of many) a program that can increase/decrease the number of products by clicking a button as shown here:
HTML
<body>
<table>
<tr>
<td>Shirt</td>
<td>2$</td>
<td>
<form id='shirt' method='POST' action='' >
<input type='button' value='-' class='qtyminus' field='shirt_count' />
<input type='text' name='shirt_count' value='0' class='qty' readonly="readonly"/>
<input type='button' value='+' class='qtyplus' field='shirt_count' />
</form>
</td>
</tr>
<tr>
<td>Suit</td>
<td>3$</td>
<td>
<form id='suit' method='POST' action='#' >
<input type='button' value='-' class='qtyminus' field='suit_count' />
<input type='text' name='suit_count' value='0' class='qty' readonly="readonly"/>
<input type='button' value='+' class='qtyplus' field='suit_count' />
</form>
</td>
</tr>
</table>
<h4>
Total items: <span id="displayCount">0</span>
<p>
Total price: <span id="displayCount">0</span>
</h4>
</body>
JavaScript
jQuery(document).ready(function(){
$('.qtyplus').click(function(e){
e.preventDefault();
fieldName = $(this).attr('field');
var currentVal = parseInt($('input[name='+fieldName+']').val());
if (currentVal == 10) {
$('input[name='+fieldName+']').val(currentVal);
}
else if (!isNaN(currentVal) ) {
$('input[name='+fieldName+']').val(currentVal + 1);
}
else {
$('input[name='+fieldName+']').val(0);
}
});
$('.qtyminus').click(function(e) {
e.preventDefault();
fieldName = $(this).attr('field');
var currentVal = parseInt($('input[name='+fieldName+']').val());
if (!isNaN(currentVal) && currentVal > 0) {
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
$('input[name='+fieldName+']').val(0);
}
});
});
Also can be seen here: http://jsfiddle.net/51ob29sL/
But the problem is, I want the 'total items' to increase/decrease as I click on the buttons. Is there a way to call 2 functions on 1 click?
Also, for the 'total price' part, I want to add the items' respective price into the variable. I feel like I might need to create an object for each item, but failed trying to do so.
Any help or tips would be appreciated.
Welcome to stack overflow :-)
Please make sure you search Stack overflow before asking your own question to avoid getting down voted...
As answered here... jQuery - Append an event handler to preexisting click event
You can add another function to click even by calling...
$('.qtyminus').click(function(e) {
// Function code here
})
But you can just create a function that does what you want it to do, something like this ( assuming id of price span is displayPrice not duplicate displayCount )...
function updateItemsAndPrice() {
var suits = parseInt($('input[name=suit_count]').val()),
shirts = parseInt($('input[name=shirt_count]').val());
$('#displayCount').html(suits + shirts)
$('#displayPrice').html(suits * 3 + shirts * 2)
}
And call it in the same event handlers at the bottom so that after updating the value price and total items are recalculated...
$('.qtyplus').click(function(e){
// Your other code
updateItemsAndPrice();
});
$('.qtyminus').click(function(e) {
// Your other code
updateItemsAndPrice();
});
Here's a fiddler... but try to do without looking at it first ;-)
http://jsfiddle.net/51ob29sL/4/
As #guest271314 said, ids must be unique. Luckily you only had one instance of breaking that rule.
Here is what you need to add to the bottom of each click function:
var shirts = parseInt($("input[name='shirt_count']").val());
var shirtsPrice = shirts * 2;
var suits = parseInt($("input[name='suit_count']").val());
var suitsPrice = suits * 3;
$("#displayCountItems").text(shirts + suits);
$("#displayCountPrice").text(shirtsPrice + suitsPrice);
Get the values from each, add them, display them
Get the values from each, multiply by price, display them
Changed ids:
Total items: <span id="displayCountItems">0</span>
Total price: <span id="displayCountPrice">0</span>
Fiddle: http://jsfiddle.net/51ob29sL/2/

javascript checkbox validation checking

I have problem with my checkbox validation on my Tip Area Soccer Game. So if the user likes to tip a game, he must have to use 2 inputs field and the confirmation checkbock. But if the user uses 2 inputs fields and "more than one" confirmation checkbox, then he must get an alert error message. Because the right combination consists from "2 input fields + confimration checkbox" Here, in my screenshot you see the right combination for the green submit button:
And in the second screenshot you see the error combination:
I don't have any idea of how to code the alert for the error message on the display if the user uses the second combination.
Here's my Javascript code:
function chkAddTip(){
var inputs = document.getElementById('AddTip').getElementsByTagName('input');
// boolean flag
var foundValid = false;
// early exit the loop if at least one valid bet has been found
for (var i = 0; i < inputs.length && !foundValid; i += 3){
if (inputs[i].type !== "submit" && (inputs[i].value && inputs[i + 1].value && inputs[i + 2].checked)) {
// set the flag to true when a valid bet is found
foundValid = true;
}
}
// determine the return value depending on the flag
if (foundValid) {
return true;
}
else {
alert("Bitte deinen Tipp und die Bestättigung abgeben.")
inputs[0].focus();
return false;
}
And here my form code:
<form action="Ctipservlet" id="AddTip" onsubmit="return chkAddTip()" method="POST">
<div id="inhalt"><h1>Tip Area</h1>
<table>
<tbody>
<tr>
<th>Playdate</th>
<th>Playtime</th>
<th>Games</th>
<th>Your Tip</th>
<th>Confirmation</th>
</tr>
<tr>
<td>21.07.</td>
<td>19:30 Uhr</td>
<td>Schalke - Bayern</td>
<td><input style="width:30px!important; text-align: center;" type="text" name="team_a0" maxlength="2" size="2">:<input style="width:30px!important; text-align: center;" type="text" name="team_b0" maxlength="2" size="2"></td>
<td><input type="checkbox" name="check0"></td>
</tr>
<tr>
<td>22.07.</td>
<td>20:30 Uhr</td>
<td>Dortmund - Leverkusen</td>
<td><input style="width:30px!important; text-align: center;" type="text" name="team_a1" maxlength="2" size="2">:<input style="width:30px!important; text-align: center;" type="text" name="team_b1" maxlength="2" size="2"></td>
<td><input type="checkbox" name="check1"></td>
</tr>
<tr>
<td>23.07.</td>
<td>15:30 Uhr</td>
<td>Wolfsburg - Nürnberg</td>
<td><input style="width:30px!important; text-align: center;" type="text" name="team_a2" maxlength="2" size="2">:<input style="width:30px!important; text-align: center;" type="text" name="team_b2" maxlength="2" size="2"></td>
<td><input type="checkbox" name="check2"></td>
</tr>
</tbody>
</table>
<input class="button_green" type="submit" name="tip" value="Submit Tip">
<input class="button_blue" onclick="this.form.onsubmit = null" type="submit" name="back" value="Back">
</div>
</form>
I hope someone have idea for this checking
We talked in chat, looked at this. Below is my solution but first... this is badly structured. You are doing validation and form submission in one step. I would break it up in to more then one. It just makes debugging/extension easier in the long run. I would validate inputs first. Save into object. Send to submit function. Then submit to DB. This right now is trying to do all that in one function. Anyway....
The problem is the loop for checking if there are inputs. When it finds the first true result it will call a submit and exit the function.
That's why you can input 2 fields, a checkbox and other checkboxes and foundValid is true.
My fix was to check for invalid input first. Have an outer boolean as an error. If it passes it submits. The only issue with it right now is empty fields will return a true condition and submit. Check the JS Fiddle http://jsfiddle.net/Komsomol/EDdUU/4/
var error = false;
var results = [];
function chkAddTip() {
var inputs = document.getElementById('AddTip').getElementsByTagName('input');
console.log(inputs);
// early exit the loop if at least one valid bet has been found
for (var i = 0; i < inputs.length; i += 3) {
if (!inputs[i].value && !inputs[i + 1].value && inputs[i + 2].checked) {
console.log("inputs inputed wrong!");
error = true;
} else {
results.push(inputs[i].value,inputs[i + 1].value,inputs[i + 2].checked);
}
}
submit();
}
function submit(){
console.log(results, error);
if(error == true){
alert("error in inputs");
} else {
alert("posting to server");
}
}

Categories

Resources