Im doing JS exercises. The task is:
Write a JavaScript program to check whether two given integer values are in the range 50..99 (inclusive). Return true if either of them are in the said range.
Task is easy, I took two numbers from two inputs.
Is there possibility to take two numbers from only one input?
and start function like this:
function task28(fnum, snum){}
Below is mine solution with two inputs.
<input type="text" id="task28a" class="form-control" placeholder="write number" aria-label=""
aria-describedby="basic-addon2">
<input type="text" id="task28b" class="form-control" placeholder="write number" aria-label=""
aria-describedby="basic-addon2">
</br>
<button type="button" class="btn btn-dark btn-sm" onclick="task28()">Check</button>
<p class="answer" id="task28ans"></p>
<script>
function task28() {
let fnum = document.getElementById("task28a").value;
let snum = document.getElementById("task28b").value;
if (
(fnum >= 50 && fnum <= 99) && (snum >= 50 && snum <= 99)
) {
document.getElementById("task28ans").innerHTML = "true";
} else {
document.getElementById("task28ans").innerHTML = "false";
}
}
</script>
I'd suggest you to use a form and run a function on submit.
This can also simplify retrieve your values
function DoSubmit(){
var a = document.myform.myinput.value;
var b = document.myform.message.value;
console.log(a,b)
}
<form name="myform" onsubmit="DoSubmit();">
<input type="text" name="myinput" value="" />
<input type="text" name="message" value="" />
<input type="submit" name="submit" />
</form>
Check below code....
function task28() {
let tempVar = document.getElementById("task28a").value;
let splitArray = tempVar.split(" ");
if(splitArray.length == 2)
{
let fnum = parseInt(splitArray[0]);
let snum = parseInt(splitArray[1]);
if ((fnum >= 50 && fnum <= 99) && (snum >= 50 && snum <= 99)) {
document.getElementById("task28ans").innerHTML = "true";
} else {
document.getElementById("task28ans").innerHTML = "false";
}
}
}
<input type="text" id="task28a" class="form-control" placeholder="Enter number" aria-label="" aria-describedby="basic-addon2">
</br>
<button type="button" class="btn btn-dark btn-sm" onclick="task28()">Check</button>
<p class="answer" id="task28ans"></p>
Related
Learning Javascript and trying to work out the best way to validate a text and number fields on a form.
I have the following html form:
> <form id="captureLegoSets">
<label for="setName">Lego Set Name</label><br>
<input class="input input1" type="text" id="setName" name="setName" value=" ">*<br>
<label for="setTheme">Set Theme</label><br>
<input class="input input1" type="text" id="setTheme" name="setTheme" value=" "><br>
<label for="setReferenceNumber">Reference Number</label><br>
<input class="input input1" type="number" id="setReferenceNumber" name="setReferenceNumber" value="0">*<br>
<label for="setPieceCount">Piece Count</label><br>
<input class="input input1" type="number" id="setPieceCount" name="setPieceCount" value="0">*<br>
<br>
<input class="input input2" type="button" value="Save Set" onclick="captureLegoSets.captureSets()">
<input class="input input2" type="reset" value="Reset Values">
</form>
And attached Javascript (forgive the numerous console.log statements):
this.captureSets = function(){
let setName = " ";
let setTheme = " ";
let setReferenceNumber = 0;
let setPieceCount = 0;
let formFields = document.querySelectorAll(".input1");
console.log(formFields);
for (let i=0; i < formFields.length; i++) {
console.log(formFields[i]);
console.log(formFields[i].id);
console.log(formFields[i].value);
if ((+document.getElementById(formFields[i].id).value) > 0 | (+document.getElementById(formFields[i].id).length) !== null) {
console.log(formFields[i].id + " = " + formFields[i].value);
if(formFields[i].id === "setName"){
setName = +document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setTheme") {
setTheme = +document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setReferenceNumber") {
setReferenceNumber = +document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setPieceCount") {
setPieceCount = +document.getElementById(formFields[i].id).value;
}
console.log(formFields);
} else {
alert("Please add non-zero values to " + formFields[i].id);
}
}
}
The problem I'm experiencing if that the else statement keeps triggering for the text fields if I only check the .value, but if I check the .length, it doesn't trigger at all.
I know I could probably put together a bunch of if statements to check for null, empty and so on, but I'm assuming this would just be poor coding on my part. Is there a better/more concise way of checking for valid inputs?
First you have provided default values to all your text fields, which let the following if check resulting in true, since you have provided default values as " " ( " " is not a null )
if ((document.getElementById(formFields[i].id).value > 0) || (document.getElementById(formFields[i].id).length !== null))
In the above expression you have used !== instead of !=
You used | not || for or operation
Remove + before document ( I don't understand why you have added those. Please explain
Hence,
remove default values / check for right conditions in the conditional statements,
use a p tag to display all the errors in the bottom. I have provided a simple example of concatenating the errors, you can also use an array to collect the errors. In the best case a separate error text right below each text field is awesome.
HTML
<form id="captureLegoSets">
<label for="setName">Lego Set Name</label><br />
<input
class="input input1"
type="text"
id="setName"
name="setName"
/>*<br />
<label for="setTheme">Set Theme</label><br />
<input
class="input input1"
type="text"
id="setTheme"
name="setTheme"
/><br />
<label for="setReferenceNumber">Reference Number</label><br />
<input
class="input input1"
type="number"
id="setReferenceNumber"
name="setReferenceNumber"
/>*<br />
<label for="setPieceCount">Piece Count</label><br />
<input
class="input input1"
type="number"
id="setPieceCount"
name="setPieceCount"
/>*<br />
<br />
<input
class="input input2"
type="button"
value="Save Set"
onclick="captureSets()"
/>
<input class="input input2" type="reset" value="Reset Values" />
</form>
<p id="error-text"></p>
JS
captureSets = function () {
let setName = "";
let setTheme = "";
let setReferenceNumber = 0;
let setPieceCount = 0;
let errorText = "";
let formFields = document.querySelectorAll(".input1");
for (let i = 0; i < formFields.length; i++) {
if (
(document.getElementById(formFields[i].id).value > 0) ||
(document.getElementById(formFields[i].id).length != null)
) {
if (formFields[i].id === "setName") {
setName = document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setTheme") {
setTheme = document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setReferenceNumber") {
setReferenceNumber = document.getElementById(
formFields[i].id
).value;
}
if (formFields[i].id === "setPieceCount") {
setPieceCount = document.getElementById(formFields[i].id).value;
}
} else {
alert("Please add non-zero values to " + formFields[i].id);
}
}
if (!setName || setName == "") {
errorText += " Fill the name text field <br>";
}
if (!setPieceCount) {
errorText += " Fill the piece count text field <br>";
}
if (!setTheme || setTheme == "") {
errorText += " Fill the theme text field <br>";
}
if (!setReferenceNumber) {
errorText += " Fill the reference number text field <br>";
}
document.getElementById("error-text").innerHTML = errorText;
};
This may or may not help you, but I think, this is easier for you to check this directly by pattern attribute. You just need to put some regex.
An HTML form with an input field that can contain only three letters (no numbers or special characters):
<form>
<label for="country_code">Country code:</label>
<input
type="text" id="country_code" name="country_code"
pattern="[A-Za-z]{3}"
title="Three letter country code">
</form>
https://www.w3schools.com/tags/att_input_pattern.asp
I have the following html and javascript code for validation on the input fields, this was working with the one input field for first name but since I tried to extend my code by adding a new input field for last name now the form validation has stopped working as follows:
function myFunction() {
let x = document.getElementsByName("first_name").[0]value;
let y = document.getElementsByName("last_name")[0].value;
let text;
text = "";
if (x == '' || x == null) {
text = "Input not valid";
}
document.getElementById("first_name_errors").innerHTML = text;
}
if (y == '' || y == null) {
text = "Input not valid";
}
document.getElementById("last_name_errors").innerHTML = text;
}
document.addEventListener('invalid', (function () {
return function (e) {
e.preventDefault();
document.getElementsByName("first_name").focus();
document.getElementsByName("last_name").focus();
};
})(), true);
</head>
<body>
<input type="text" name="first_name" placeholder="first name" name class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="myFunction()">
<br><br>
<input type="text" name="last_name" placeholder="last name" name class="input_fields" required>
<div class="error-message" id="last_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_lname" onclick="myFunction()">
How can I get this back working with the extra input field last name added? Thanks in advance
there are many errors here. you may find them by your own by debugging your console.log
error, at let x = document.getElementsByName("first_name").[0]value;
there are a to many }
eventlisteners need to be on the input and shouldn't be inside the check function
there are empty name attributes on your inputs
fixing it blind it would be something like:
let firstName = document.getElementsByName('first_name')[0];
let lastName = document.getElementsByName('last_name')[0];
function checkValid() {
let x = firstName.value;
let y = lastName.value;
let text;
text = '';
if (x == '' || x == null) {
text = 'Input not valid';
}
document.getElementById('first_name_errors').innerHTML = text;
if (y == '' || y == null) {
text = 'Input not valid';
}
document.getElementById('last_name_errors').innerHTML = text;
}
firstName.addEventListener('invalid', function () {
firstName.focus();
});
lastName.addEventListener('invalid', function () {
lastName.focus();
});
<input type="text" name="first_name" placeholder="first name" class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="checkValid()">
<br><br>
<input type="text" name="last_name" placeholder="last name" class="input_fields" required>
<div class="error-message" id="last_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_lname" onclick="checkValid()">
I want to verify and validate a form in HTML, and insert messages in Front if necessary ("eg.Pseudo/Username not long enough"), which will serve as a "new user" form for a website.
I want to start by understanding my mistake for the "Pseudo" verification and validation.
I currently have the following in HTML:
<form id="formNouveau" onsubmit="return valideForm2()">
<div>
<div id="msgPseudo"></div>
<label for="pseudo">Pseudo</label>
<br>
<input type="text" name="pseudo" id="pseudo" required>
</div>
<div>
<div id="msgEmail"></div>
<label for="email">Email</label>
<br>
<input type="email" name="email" id="email" required>
</div>
<div>
<div id="msgPass"></div>
<label for="password">Mot de passe</label>
<br>
<input type="password" name="password" id="password" placeholder="*******" required>
</div>
<div>
<div id="msgPassRep"></div>
<label for="passwordRepeat">Repeat your password</label>
<br>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="*******" required>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Create an account">
</div>
</form>
and the following in JS (focusing on the pseudo validation):
function valideForm(){
var valPseudo = document.getElementById("pseudo").value;
var msgPseudo = document.getElementById("msgPseudo");
function valPseudo(text)
let letters = 'abcdefghijklmnopqrstuvwxyz'
let numbers = '0123456789'
let letterCount = 0
let numberCount = 0
for (let character of text.toLowerCase()) {
if (letters.includes(character))
++letterCount
else if (numbers.includes(character))
++numberCount
else
return false //A non [a-zA-Z0-9] character was present
}
if (valPseudo == "")
alert ("Please write a pseudo");
if (letterCount + numberCount > 40)
alert ("Pseudo is too long") //The name is too long
if (letterCount + numberCount < 5)
alert ("Pseudo is too short") //The name is too short
if (letterCount < 1)
alert ("one letter needed at least") //There aren't enough [a-zA-Z] characters
if (numberCount < 1)
alert ("one number needed at least") //There aren't enough [0-9] characters
return 0 //Everything is okay!
}
}
What do you think?
Thank you!
You have a mix of variable names in the function and a sub function with incorrect syntax. You're not preventing the form from submitting. Fixed both and it works:
function valideForm(e) {
e.preventDefault();
var valPseudo = document.getElementById("pseudo").value;
var msgPseudo = document.getElementById("msgPseudo");
let letters = 'abcdefghijklmnopqrstuvwxyz'
let numbers = '0123456789'
let letterCount = 0
let numberCount = 0
for (let character of valPseudo.toLowerCase()) {
if (letters.includes(character))
++letterCount
else if (numbers.includes(character))
++numberCount
else
return false //A non [a-zA-Z0-9] character was present
}
if (valPseudo == "")
alert("Please write a pseudo");
if (letterCount + numberCount > 40)
alert("Pseudo is too long") //The name is too long
if (letterCount + numberCount < 5)
alert("Pseudo is too short") //The name is too short
if (letterCount < 1)
alert("one letter needed at least") //There aren't enough [a-zA-Z] characters
if (numberCount < 1)
alert("one number needed at least") //There aren't enough [0-9] characters
return 0 //Everything is okay!
}
document.getElementsByTagName('form')[0].addEventListener('submit', valideForm);
<form id="formNouveau">
<div>
<div id="msgPseudo"></div>
<label for="pseudo">Pseudo</label>
<br>
<input type="text" name="pseudo" id="pseudo" required>
</div>
<div>
<div id="msgEmail"></div>
<label for="email">Email</label>
<br>
<input type="email" name="email" id="email" required>
</div>
<div>
<div id="msgPass"></div>
<label for="password">Mot de passe</label>
<br>
<input type="password" name="password" id="password" placeholder="*******" required>
</div>
<div>
<div id="msgPassRep"></div>
<label for="passwordRepeat">Repeat your password</label>
<br>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="*******" required>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Create an account">
</div>
</form>
function valideForm2(e) {
e.preventDefault();
var valPseudo = document.getElementById("pseudo").value;
var msgPseudo = document.getElementById("msgPseudo");
console.log(valPseudo);
function validate(text) {
let letters = "abcdefghijklmnopqrstuvwxyz";
let numbers = "0123456789";
let letterCount = 0;
let numberCount = 0;
for (let character of text.toLowerCase()) {
if (letters.includes(character)) ++letterCount;
else if (numbers.includes(character)) ++numberCount;
else return false; //A non [a-zA-Z0-9] character was present
}
if (text == "") alert("Please write a pseudo");
if (letterCount + numberCount > 40) alert("Pseudo is too long"); //The name is too long
if (letterCount + numberCount < 5) alert("Pseudo is too short"); //The name is too short
if (letterCount < 1) alert("one letter needed at least"); //There aren't enough [a-zA-Z] characters
if (numberCount < 1) alert("one number needed at least"); //There aren't enough [0-9] characters
return 0; //Everything is okay!
}
validate(valPseudo);
}
const form = document.getElementById("formNouveau");
form.addEventListener("submit", valideForm2);
Try this JS code instead, it has the same functionality but has some modifications, the main problem was regarded to e.preventDefault() which forces page not to reload. Moreover you had some little bugs. For more information on preventDefault you can visit link: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
You're better off testing the input against a REGEX expression rather than testing for each failure case...
There a numerous REGEX testers and cheat-sheets online for what you're trying to do.
I want when the submit button is clicked, Compare the amount of income and expenses and the result will be displayed as a pop-up.
But it does not work. Where do you think the problem
var income = document.getElementById('income').value;
var outgo = document.getElementById('outgo').value;
function incomeCalculation() {
if (income > outgo) {
alert('income > outgo');
} else if (outgo > income) {
alert('outgo > income');
}
}
<label>Income:</label>
<input type="text" id="income">
<br><br>
<label>Outgo: </label>
<input type="text" id="outgo">
<br><br>
<input type="submit" id="submit" onclick="incomeCalculation()">
There are a couple of problems here:
You need to parse your inputs as numbers, as inputs will return string values. (Use either parseFloat or parseInt)
You want to get the values when the button is clicked, not when the document loads, so the variables should be set inside the function.
function incomeCalculation() {
var income = parseFloat(document.getElementById('income').value);
var outgo = parseFloat(document.getElementById('outgo').value);
if (income > outgo) {
alert('income > outgo');
} else if (outgo > income) {
alert('outgo > income');
}
}
<label>Income:</label>
<input type="text" id="income">
<br><br>
<label>Outgo: </label>
<input type="text" id="outgo">
<br><br>
<input type="submit" id="submit" onclick="incomeCalculation()">
function incomeCalculation() {
var income = document.getElementById('income').value;
var outgo = document.getElementById('outgo').value;
if (income > outgo) {
alert('income > outgo');
} else if (outgo > income) {
alert('outgo > income');
}
}
I have a site I'm working on where I have made a javascript calculator and I need all 3 forms in the page to round to 2. I have used toFixed(2) on my first form. The other 2 forms still display all decimal points even though I have used .toFixed(2) on them. Any ideas
<script type="text/Javascript">
// Begin calculations
function resetCalc() {
document.forms[0].elements[1]="";
}
function calcRect() {
if(validNumber(document.getElementById('length'), 'length') == true) {
if(validNumber(document.getElementById('width'), 'width') == true) {
var length = (document.getElementById('length').value)
var width = (document.getElementById('width').value)
var prodRect = ( length * width / 9 ) .toFixed(2)
document.getElementById('ansRect').value = prodRect
}
}
}
function calcCirc() {
if(validNumber(document.getElementById('diameter'), 'diameter') == true) {
var diameter = (document.getElementById('diameter').value)
var prodCirc = (diameter / 2) * (diameter / 2) * 3.14 /9 .toFixed(2)
document.getElementById('ansCirc').value = prodCirc
}
}
function calcTria() {
if(validNumber(document.getElementById('base'), 'base') == true) {
if(validNumber(document.getElementById('height'), 'height') == true) {
var base = (document.getElementById('base').value)
var height = (document.getElementById('height').value)
var prodTria = (base * .5) * height / 9 .toFixed(2)
document.getElementById('ansTria').value = prodTria
}
}
}
// End Calculations
// BEGIN Validate Values entered
//Requires field that contians value being evaluated
function validNumber(varInput, fieldName) {
if (varInput.value == null) {
alert('Please enter a value for the ' + fieldName + ' field');
varInput.focus();
return false;
}
if (IsNumeric(varInput.value) == false) {
alert('Please enter only numbers or decimal points in the ' + fieldName + ' field');
varInput.focus();
return false;
}
return true;
}
// END Validation
// check for valid numeric strings
function IsNumeric(strString) {
var strValidChars = "0123456789.";
var strChar;
var blnResult = true;
if (strString.length == 0) return false;
// test strString consists of valid characters listed above
for (i = 0; i < strString.length && blnResult == true; i++)
{
strChar = strString.charAt(i);
if (strValidChars.indexOf(strChar) == -1)
{
blnResult = false;
}
}
return blnResult;
}
//
</script>
And the html
<form name="sodCalc" id="formEnquire" action="">
<div id="ctl00_body_sodCalc1_validationSummarySodCalc" style="color:Red;display:none;"> </div>
<p><strong>For a rectangular shaped area</strong></p>
<p>
<label>Length</label>
<input name="length" id="length" type="text" tabindex="1" />
<label>Width</label>
<input name="width" id="width" type="text" tabindex="1" />
<label>Result</label>
<input type="text" value="0" name="ansRect" id="ansRect" />
<br class="clear"/>
<input type="button" value="Calculate" onclick="calcRect()" name="btnRect" id="btnRect" />
<input type="reset" value="Reset" onclick="resetCalc()" name="reset" id="reset" />
</p>
</form>
<form name="sodCalc" id="formEnquire" action="">
<div id="ctl00_body_sodCalc1_validationSummarySodCalc" style="color:Red;display:none;"> </div>
<p><strong>For a circle area </strong></p>
<p>
<label>Diameter Of Circle</label>
<input name="diameter" id="diameter" type="text" tabindex="1" />
<label>Result</label>
<input type="text" size="6" value="0" name="ansCirc" id="ansCirc" />
<br class="clear"/>
<input type="button" value="Calculate" onclick="calcCirc()" name="btnCirc" id="btnCirc" />
<input type="reset" value="Reset" onclick="resetCalc()" name="reset" id="reset" />
` </p>
</form>
<form name="sodCalc" id="formEnquire" action="">
<div id="ctl00_body_sodCalc1_validationSummarySodCalc" style="color:Red;display:none;"> </div>
<p><strong>For a triangle area </strong></p>
<p>
<label>Base</label>
<input name="base" id="base" type="text" tabindex="1" />
<label>Height</label>
<input name="height" id="height" type="text" tabindex="1" />
<label>Result</label>
<input type="text" size="6" value="0" name="ansTria" id="ansTria" />
<br class="clear"/>
<input type="button" value="Calculate" onclick="calcTria()" name="btnTria" id="btnTria" />
<input type="reset" value="Reset" onclick="resetCalc()" name="reset" id="reset" />
</p>
</form>
You need to parenthesize the expressions in the second two functions like you did in the first one:
var prodTria = ( (base * .5) * height / 9 ).toFixed(2)
Without the extra parentheses, all that was being converted in that one was the 9.