I'm supposed to write javascript code for an html page that will calculate a persons BMI and tell them what it means (the number). The rules of the test were to not change the html on the page, but to just write the javascript code and link it to the html page. That's all. I have copied the html page just in case you guys might wanna have a look at it. Here is what the BMI Calculator is supposed to do using javascript:
Person enters name, selects gender, enters weight and height. The application will calculate the persons BMR, BMI, and tell what it means (i.e. saying "you are too thin", "you are healthy", or "you are overweight").
and it will display an image of a thin, healthy, or overweight person which is a png image.
If they do not enter a name, an error message prompts them to enter a name. The name must be at least five characters long.
If they do not select a gender, then an error message prompts them to please select a gender. The gender is represented by a radio button. The user selects male or female.
If the user does not enter a weight, an error message prompts them to please enter a weight.
If height is not entered, an error message prompts them to please enter a height.
If you are a male, you're BMR is calculated as: BMR = 10*(weight+6.25)(height-5)(age+5).
If you are a female, you're BMR is calculated as: BMR = 10*(weight+6.25)(height-5)(age-161).
If the BMI is less than 18.5: "you are too thin".
If the BMI is between 20 to 25: "you are healthy".
If the BMI is greater than 25: "you are overweight".
Also, please don't put the question on hold or delete it. This is important for me and I need help. If you want help, please don't. It took me a long time to write this question.
Here is the html that I am supposed to write the javascript code for:
<html>
<head>
<title> BMI Calculator </title>
<style>
label {
display: inline-block;
width: 80px;
height: 25px;
}
button {
height:30px;
margin: 5px 0px;
}
fieldset {
display: inline-block;
}
#errMsg {
color: red;
}
#frm {
float: left;
width: 30%;
}
#imgSec {
float: left;
padding: 5px 0px;
border-left: 3px solid darkblue;
}
</style>
<!-- link to javascript file -->
<script type="text/javascript" src="BMI_javascript.js">
</script>
</head>
<body>
<div id="title"><h3>BMI Calculator</h3></div>
<section id="frm">
<form name="bmiForm" onsubmit="return false;">
<fieldset>
<legend>Enter your Details:</legend>
<label for="user">Name:</label>
<input type="text" id="user" size="25" required> <br />
<label for="gender">Gender:</label>
<input type="radio" id="rbMale" name="gender"> Male
<input type="radio" id="rbFemale" name="gender">Female <br />
<label for="age">Age:</label>
<input type="number" id="age" size="10" required> <br />
<label for="weight">Weight(kg):</label>
<input type="number" id="weight" size="10" required> <br />
<label for="height">Height(cm):</label>
<input type="number" id="height" size="10" required> <br />
<div id="errMsg"></div>
</fieldset>
<br>
<button onclick="calculate()">Calculate BMI</button>
<button type="reset" onclick="clearErr()">Reset</button>
<br>
<fieldset>
<legend>Result:</legend>
<label for="bmr">Your BMR: </label>
<input type="text" name="bmr" id="bmr" size="18" readonly><br />
<label for="bmi">Your BMI: </label>
<input type="text" name="bmi" id="bmi" size="10" readonly><br />
<label for="meaning">This Means: </label>
<input type="text" name="meaning" id="meaning" size="25" readonly><br/>
</fieldset>
</section>
<section id="imgSec">
<img id="img" src="" height="250px">
</section>
</form>
</body>
</html>
And here is the javascript I wrote for it. I know it's horrible. The problem is the code does not work. Nothing works.
function GenderType() {
var GenderType = document.getElementsByName("rbMale","rbFemale");
if(rbMale == "Male") {
GenderType.innerHTML = "Male";
} else {
rbFemale == "Female";
GenderType.innerHTML = "Female";
}
}
function validate() {
var name = document.getElementById("name");
var age = document.getElementById("age");
var male = document.getElementById("male");
var female = document.getElementById("female");
var weight = document.getElementById("weight");
var height = document.getElementById("height");
error = false;
var reName = /^[a-zA-Z ]{5,}$/;
if (reName.test(name.value) == false) {
nameError.innerHTML = "Name must be eight letters or more";
error = true;
} else {
nameError.innerHTML = "";
}
age = parseInt(age.value);
if ( isNaN(age) || age < 0 || age > 65) {
ageError.innerHTML = "Age must be in range 0-65";
error = true;
} else {
ageError.innerHTML = "";
}
weight = parseInt(weight.value);
if ( isNaN(weight) || weight < 0) {
weightError.innerHTML = "Weight must be greater than 0";
error = true;
} else {
weightError.innerHTML = "";
}
height = parseInt(height.value);
if (isNaN(height) || height < 0) {
heightError.innerHTML = "height must be greater than 0"
error = true;
} else {
heightError.innerHTML = "";
}
if ( !male.checked & !female.checked) {
genderError.innerHTML = "Select value";
error = true;
} else {
genderError.innerHTML = "";
}
}
function BMRCalculate () {
if ( validate()==false ) {
var GenderType = document.getElementById("rbMale","rbFemale").value;
var age = document.getElementById("age").value;
var female = document.getElementById("rbFemale");
var male = document.getElementById("rbMale");
var weight = document.getElementById("weight");
var height = document.getElementById("height");
var BMIValue = weight/( (height/100)*(height/100) );
var BMRValue;
var ThisMeans = document.getElementById("meaning");
if(GenderType == male) {
BMRValue = 10*(weight+6.25)*(height-5)*(age+5);
} else {
GenderType = female;
BMRValue = 10*(weight+6.25)*(height-5)*(age-161);
}
if (BMIValue<18.5) {
ThisMeans = "you are too thin";
document.write(ThisMeans);
} else if (BMIValue>18.5 && BMIValue<25) {
ThisMeans = "you are healthy";
document.write(ThisMeans);
} else {
ThisMeans = "You are not healthy";
document.write(ThisMeans);
}
}
Mate, #gavgrif gave you some very good tips, but about the code...try to start over and think the problem again.
Related
When users click submit, I've coded an error message to appear under each input field that is missing a value using DOM selectors. I also disabled the email file that opens when submit is clicked, using preventDefault().
However, when the user types into the text area, the messages don't disappear. I tried using a 'keydown' event, but I couldn't get it to work.
HTML code:
<body>
<header class="header">
<form action="mailto:me#fakeemail.com">
<fieldset>
<legend>Personal details</legend>
<p>
<label>
Full name:
<input type="text" name="fullname" id="fullname">
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label>
Street Address:
<input type="text" name="streetaddr" id="streetaddr">
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
</fieldset>
<input type="submit" value="Submit it!" class="submitIt" onsubmit="return checkForm();">
</form>
<br>
<script src="inline-error.js" charset="utf-8"></script>
<div class="returnHome">
Return Home
</div>
</header>
</body>
Javascript code:
var submitIt = document.querySelector(".submitIt");
submitIt.addEventListener("click", function checkForm(event) {
var fNameInput = document.querySelector("#fullname")
var streetAddInput = document.querySelector("#streetaddr")
if (fNameInput.value == "") {
var nameErrorMsg = document.querySelector("#nameerrormsg").style.display = "block";
event.preventDefault();
}
if (streetAddInput.value == "") {
var addrErrorMsg = document.querySelector("#addrerrormsg").style.display = "block";
event.preventDefault();
}
})
To see an immediate result in the code in its current state, hide the error messages before checking the input values.
var submitIt = document.querySelector('.submitIt');
submitIt.addEventListener('click', function checkForm(event) {
var nameErrorMsg = document.querySelector('#nameerrormsg');
var addrErrorMsg = document.querySelector('#addrerrormsg');
nameErrorMsg.style.display = 'none';
addrErrorMsg.style.display = 'none';
var fNameInput = document.querySelector('#fullname');
var streetAddrInput = document.querySelector('#streetaddr');
if (fNameInput.value == '') {
nameErrorMsg.style.display = 'block';
event.preventDefault();
}
if (streetAddrInput.value == '') {
addrErrorMsg.style.display = 'block';
event.preventDefault();
}
});
Having said that, here are some additional suggestions:
Use CSS for styling elements (not JavaScript)
Discourage inline JavaScript
Store DOM elements outside the scope of the event listener so you don't have to query the DOM every time you click
Consider utilizing the required attribute on the inputs for a quick win on styling
So...
<!-- form.html -->
<head>
<link rel="stylesheet" href="form.css">
</head>
<body>
<header class="header">
<form>
<fieldset>
<legend>Personal details</legend>
<p>
<label for="fullname">Full name:
<input type="text" name="fullname" id="fullname" required>
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label for="streetaddr">Street Address:
<input type="text" name="streetaddr" id="streetaddr" required>
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
</fieldset>
<input type="submit" value="Submit it!" class="submitIt">
</form>
</header>
<button id="returnhome">Return Home</button>
<script src="inline-error.js"></script>
</body>
/* form.css */
input:valid {
border: none;
}
input:invalid:required {
border: 1px solid red;
}
.errormsg {
display: none;
}
.show {
display: block;
}
// inline-error.js
var submitIt = document.querySelector('.submitIt');
var nameInput = document.querySelector('#fullname');
var nameError = document.querySelector('#nameerrormsg');
var addrInput = document.querySelector('#streetaddr');
var addrError = document.querySelector('#addrerrormsg');
var returnHome = document.querySelector('#returnhome');
returnHome.addEventListener('click', e => {
e.preventDefault();
history.back();
});
submitIt.addEventListener('click', event => {
const nameValue = nameInput.value;
const addrValue = addrInput.value;
if (!nameValue || !addrValue) {
event.preventDefault();
}
if (!nameValue) {
nameError.classList.add('show');
} else {
nameError.classList.remove('show');
}
if (!addrValue) {
addrError.classList.add('show');
} else {
addrError.classList.remove('show');
}
});
I am currently working with forms and javascript validation.. i have completed most of my code and am on the last step however cant seem to get it working and not sure what ive done wrong.. spent hours on this last part before i looked for help.
basically a user inputs their information into a form and then when they click submit the information get validated, and the inputed info moves onto a confirmation page.. at the moment the input i put in doesnt get validated anymore and is blank in the confirmation page..
First HTML register page
<form id="regform" method="post" action="confirm.html"
novalidate="novalidate">
<fieldset id="person">
<legend>Your details:</legend>
<p><label for="firstname">Enter your first name</label>
<input type="text" name="firstname" id="firstname" size="20"
/>
</p>
<p><label for="lastname">Enter your last name</label>
<input type="text" name="lastname" id="lastname" size="20" />
</p>
<fieldset id="species">
<legend>Species:</legend>
<label for="human">Human</label>
<input type="radio" name="species" id="human"
value="Human"/><br />
<label for="dwarf">Dwarf</label>
<input type="radio" name="species" id="dwarf"
value="Dwarf" /><br />
<label for="elf">Elf</label>
<input type="radio" name="species" id="elf"
value="Elf" /><br />
<label for="hobbit">Hobbit</label>
<input type="radio" name="species" id="hobbit"
value="Hobbit" /><br />
</fieldset>
<p><label for="age">Enter your age</label>
<input type="text" id="age" name="age" size="5">
</p>
</fieldset>
<fieldset id="trip">
<legend>Your trip:</legend>
<fieldset>
<legend>Booking:</legend>
<label for="1day">1 Day Tour - $200 </label>
<input type="checkbox" name="1day" id="1day"
value="1day" /><br />
<label for="4day">4 Day Tour - $1500</label>
<input type="checkbox" name="4day" id="4day"
value="4day" /><br />
<label for="10day">10 Day Tour - $3000</label>
<input type="checkbox" name="10day" id="10day"
value="10day" /><br />
</fieldset>
<p>
<label for="food">Menu preferences</label>
<select name="food" id="food">
<option value="none">Please select</option>
<option value="lembas">Lembas</option>
<option value="mushrooms">Mushrooms</option>
<option value="ent">Ent Draft</option>
<option value="cram">Cram</option>
</select>
</p>
<p>
<label for="partySize">Number of Travellers</label>
<input type="text" id="partySize" name="partySize" maxlength="3"
size="3" />
</p>
</fieldset>
<div id="bottom"> </div>
<p><input type="submit" value="Book Now!" />
<input type="reset" value="Reset" />
</p>
Validation for Javascript
function validate() {
var errMsg = "";
var result = true;
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
if (!firstname.match(/^[a-zA-Z]+$/)) {
errMsg = errMsg + "Your first name must only contain alpha characters\n";
result = false;
}
if (!lastname.match(/^[a-zA-Z+$]/)) {
errMsg = errMsg + "Your last name must only contain alpha characters\n";
result = false;
}
var age = document.getElementById("age").value;
if (isNaN(age)) {
errMsg = errMsg + "your age must be a number\n";
result = false;
}
else if (age < 18) {
errMsg = errMsg + " your age must be 18 or older\n";
result = false;
}
else if (age >= 10000) {
errMsg = errMsg + "your age must be between 18 and 10000\n";
result = false;
}
else {
var tempMsg = checkSpeciesAge(age);
if (tempMsg != "") {
errMsg + tempMsg;
result = false;
}
var partySize = document.getElementById("partySize").value;
if (isNaN(partySize)) {
errMsg = errMsg + "your age must be a number\n";
result = false;
}
else if (partySize < 1) {
errMsg = errMsg + " party size must be greater than 0\n";
result = false;
}
else if (age >= 100) {
errMsg = errMsg + "your party size must be less or equal to 100\n";
result = false;
}
}
var is1day = document.getElementById("1day").checked;
var is4day = document.getElementById("4day").checked;
var is10day = document.getElementById("10day").checked;
if (!(is1day || is4day || is10day)) {
errMsg = errMsg + "please select at least one trip.\n";
result = false;
}
if (document.getElementById("food").value == "none") {
errMsg = errMsg + "You must select a food preference. \n ";
result = false;
}
var human = document.getElementById("human").checked;
var dwarf = document.getElementById("dwarf").checked;
var elf = document.getElementById("elf").checked;
var hobbit = document.getElementById("hobbit").checked;
if (!(human || dwarf || elf || hobbit)) {
errMsg = errMsg + "please select a spiecies";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
}
if (result) {
storeBooking(firstname, lastname, age, species, is1day, is4day, is10day);
}
return result;
}
function getSpecies() {
var speciesName = "Unknown";
var speciesArray = document.getElementById("species").getElementsByTagName("input");
for (var i = 0; i < speciesArray.length; i++){
if (speciesArray[i].checked)
speciesName = speciesArray[i].value;
}
return speciesName;
}
function checkSpeciesAge(age) {
var errMsg = "";
var species = getSpecies();
switch(species){
case "human":
if (age > 120) {
errMsg = "you cannot be a Human and over 120. \n";
}
break;
case "dwarf":
case "hobit":
if (age > 150 ){
errMsg = " YOu can not be a " + species + " and over 150 .\n ";
}
break;
case "elf":
break;
default:
errMsg = " we dont allow your kind on our tours. \n";
}
return errMsg;
}
function storeBooking(firstname, lastname, age, species, is1day, is4day, is10day){
var trip= "";
if(is1day) trip ="1day";
if(is4day) trip +=", 4day";
is(is10day) trip += ", 10day";
sessionStorage.trip = trip;
sessionStorage.firstname= firstname;
sessionStorage.lastname= lastname;
sessionStorage.age = age;
sessionStorage.species= species;
sessionStorage.partySize= partySize;
sessionStorage.food = food;
alert ("Trip stored: " + sessionStorage.trip);
}
function init() {
var regForm = document.getElementById("regform");
regForm.onsubmit = validate;
}
window.onload = init;
Confirm HTML
<form id="bookform">
<fieldset>
<legend>Your Booking</legend>
<p>Your Name: <span id="confirm_name"></span></p>
<p>Species: <span id="confirm_species"></span></p>
<p>Age: <span id="confirm_age"></span></p>
<p>Trips booked: <span id="confirm_trip"></span></p>
<p>Food Preference: <span id="confirm_food"></span></p>
<p>Number of beings: <span id="confirm_partySize"></span></p>
<p>Total Cost: $<span id="confirm_cost"></span></p>
<input type="hidden" name="firstname" id="firstname" />
<input type="hidden" name="lastname" id="lastname" />
<input type="hidden" name="age" id="age" />
<input type="hidden" name="species" id="species" />
<input type="hidden" name="trip" id="trip" />
<input type="hidden" name="food" id="food" />
<input type="hidden" name="partySize" id="PartySize" />
<input type="hidden" name="cost" id="cost" />
<p><label for="date">Preferred Date</label>
<input type="text" id="date" name="bookday" required="required" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" title="Format dd/mm/yyyy" maxlength="10" size="10" />
</p>
<input type="submit" value="Confirm Booking" />
<button type="button" id="cancelButton">Cancel</button>
</fieldset>
Javascrips file 2 to bring the info over to the confirmation
function validate(){
var errMsg = "";
var result = true;
return result;
function calcCost(trips, partySize){
var cost = 0;
if (trips.search("1day") != -1) cost = 200;
if (trips.search("4day")!= -1) cost += 1500;
if (trips.search("10day")!= -1) cost += 3000;
return cost * partySize;
}
function getBooking(){
var cost = 0;
if(sessionStorage.firstname != undefined){
//confirmation text
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_age").textContent =sessionStorage.age;
document.getElementById("confirm_trip").textContent = sessionStorage.trip;
document.getElementById("confirm_species").textContent = sessionStorage.species;
document.getElementById("confirm_food").textContent =sessionStorage.food;
document.getElementById("confirm_partySize").textContent = sessionStorage.partySize;
cost = calcCost(sessionStorage.trip, sessionStorage.partySize);
document.getElementById("confirm_cost").textContent = cost;
//fill hidden fields
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("age").value = sessionStorage.age;
document.getElementById("species").value = sessionStorage.species;
document.getElementById("food").value = sessionStorage.food;
document.getElementById("partySize").value = sessionStorage.partySize;
document.getElementById("cost").value = cost;
}
}
function init () {
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validate;
}
window.onload = init;
There are a couple of syntax errors that should be clearly visible when you open your browser console:
- errMsg + tempMsg; is not a complete statement,
- is(is10day) trip += ", 10day"; is not valid, and
- storeBooking doesn't have a parameter called partySize
I see a couple of logic errors too:
- checkSpeciesAge will never return an empty string as validate expects, and
- the section of code that attempts to validate partySize has several errors (including that this entire structure is nested inside the age-validation section's else block.)
A few console.log statements could go a long way toward identifying where your variables contain values that you don't expect if there are still bugs to track down after correcting these issues. Good luck!
I tried to fix this, and make some changes in your code. according to your requirement
follow the link of jsfiddle; https://jsfiddle.net/dupinderdhiman/vno15jku/32/
<form id="bookform">
<fieldset>
<legend>Your Booking</legend>
<p>Your Name: <span id="confirm_name"></span></p>
<p>Species: <span id="confirm_species"></span></p>
<p>Age: <span id="confirm_age"></span></p>
<p>Trips booked: <span id="confirm_trip"></span></p>
<p>Food Preference: <span id="confirm_food"></span></p>
<p>Number of beings: <span id="confirm_partySize"></span></p>
<p>Total Cost: $<span id="confirm_cost"></span></p>
<input type="hidden" name="firstname" id="firstname" />
<input type="hidden" name="lastname" id="lastname" />
<input type="hidden" name="age" id="age" />
<input type="hidden" name="species" id="species" />
<input type="hidden" name="trip" id="trip" />
<input type="hidden" name="food" id="food" />
<input type="hidden" name="partySize" id="PartySize" />
<input type="hidden" name="cost" id="cost" />
<p><label for="date">Preferred Date</label>
<input type="text" id="date" name="bookday" required="required" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" title="Format dd/mm/yyyy" maxlength="10" size="10" />
</p>
<input type="submit" value="Confirm Booking"/>
<button type="button" id="cancelButton">Cancel</button>
</fieldset>
<script>
sessionStorage.trip = "4day";
sessionStorage.firstname= "firstname";
sessionStorage.lastname= "lastname";
sessionStorage.age = 21;
sessionStorage.species= "species";
sessionStorage.partySize= 10;
sessionStorage.food = "food";
function validate(){
var errMsg = "";
var result = true;
return result;
}
function calcCost(trips, partySize){
var cost = 0;
if (trips.search("1day") != -1) cost = 200;
if (trips.search("4day")!= -1) cost += 1500;
if (trips.search("10day")!= -1) cost += 3000;
return cost * partySize;
}
function loadDataFromSession(){
var cost = 0;
if(sessionStorage.firstname != undefined){
//confirmation text
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_age").textContent =sessionStorage.age;
document.getElementById("confirm_trip").textContent = sessionStorage.trip;
document.getElementById("confirm_species").textContent = sessionStorage.species;
document.getElementById("confirm_food").textContent =sessionStorage.food;
document.getElementById("confirm_partySize").textContent = sessionStorage.partySize;
cost = calcCost(sessionStorage.trip, sessionStorage.partySize);
document.getElementById("confirm_cost").textContent = cost;
//fill hidden fields
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("age").value = sessionStorage.age;
document.getElementById("species").value = sessionStorage.species;
document.getElementById("food").value = sessionStorage.food;
document.getElementById("partySize").value = sessionStorage.partySize;
document.getElementById("cost").value = cost;
}
}
function init () {
loadDataFromSession();
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validate;
}
window.onload = init;
</script>
so what is the major change:
Created one function loadDataFromSession which call on init();
remove code from getBooking() add to loadDataFromSession.
now click on submit and your form will be submit
Im trying to make a bookshop website where the customer checks the books and writes the number of copies. But the code cannot tell if the checkbox is checked and goes with the "else" option always. What needs to change?
checkb1-5 are the checkboxes element
numbcop1-5 is the number of copies entered by the user
function Checker() {
var checkb1 = document.getElementById("adult");
if (checkb1.checked){
var numbcop1 = document.getElementById(numb1);
} else{
var numbcop1 = 0;
}
var checkb2 = document.getElementById("ado");
if (checkb2.checked){
var numbcop2 = document.getElementById(numb2);
} else{
var numbcop2 = 0;
}
var checkb3 = document.getElementById("child");
if (checkb3.checked){
var numbcop3 = document.getElementById(numb3);
} else {
var numbcop3 = 0;
}
var checkb4 = document.getElementById("school");
if (checkb4.checked){
var numbcop4 = document.getElementById(numb4);
} else {
var numbcop4 = 0;
}
var checkb5 = document.getElementById("transl");
if (checkb5.checked){
var numbcop5 = document.getElementById(numb5);
} else{
var numbcop5 = 0;
}
}
Looks like there are a few things to fix before to make your function works:
When you are doing var numbcop1 = document.getElementById(numb1); you need to make sure the parameter you are adding to getElementById is correct. E.g document.getElementById('numb1') or make sure that numb1 contains an string indicating the id for the function to look at e.g var numb1 = 'adult_amount'; and then use that variable as your code does document.getElementById(numb1)
Once you get the element that is expected to have the value, if it is an input you can do var numbcop1 = document.getElementById('numb1').value; to get the number typed by the user.
Let's refactor the Adult field to have a clear example on how it works:
<input type="checkbox" data-copies="adult_copies" id="adult">
<label>adult</label>
<input type="number" id="adult_copies">
And add this to your JS and check how the values comes using a single function that can be reused for the other books:
function getChecked(event) {
let numbcop;
let copies_id = event.target.getAttribute('data-copies');
if (event.target.checked){
numbcop = document.getElementById(copies_id).value;
} else{
numbcop = 0;
}
console.log(numbcop);
}
let adult = document.getElementById("adult");
adult.addEventListener('click', getChecked);
LMK if this works for your implementation.
actually it is going with the if option not else but it is returning zero.
You must point to the value of the numb1 not just the element.
for example:
var numbcop1 = document.getElementById(numb1).value;
at least this must be coded like this (?):
var
t_elem = ['adult', 'ado', 'child','school', 'transl'],
numbcop1 = 0,
numbcop2 = 0,
numbcop3 = 0,
numbcop4 = 0,
numbcop5 = 0
;
function Checker() {
t_elem.forEach((elm,idx)=>{
window['numbcop'+(idx+1)] = (document.getElementById(elm).checked) ? document.getElementById('numb'+(idx+1)).value : 0;
})
}
Get_Books.onclick = function() {
Checker();
console.log(numbcop1, numbcop2, numbcop3, numbcop4, numbcop5);
}
label { float:left; clear: both; display:block; width:80px; margin:10px 5px; text-align: right }
input, button { float:left; display:block; margin:10px 5px }
button { clear: both }
<label for="adult">adult: </label>
<input id="adult" type="checkbox" />
<input id="numb1" type="number" value="1" />
<label for="ado">ado: </label>
<input id="ado" type="checkbox" />
<input id="numb2" type="number" value="2" />
<label for="adult">child: </label>
<input id="child" type="checkbox" />
<input id="numb3" type="number" value="3" />
<label for="school">school: </label>
<input id="school" type="checkbox" />
<input id="numb4" type="number" value="4" />
<label for="transl">transl: </label>
<input id="transl" type="checkbox" />
<input id="numb5" type="number" value="5" />
<button id="Get_Books">Books</button>
So I have this piece of HTML and JavaScript
function validate() {
const tabs = document.getElementsByClassName("tab");
const input = tabs[currentTab].querySelectorAll("input[type=tel], input[type=text], input[type=time], input[type=number], input[type=email]");
const radio = tabs[currentTab].querySelectorAll("input[type=radio]");
const select = tabs[currentTab].getElementsByTagName("select");
let valid = true;
if (radio.length == 0) {
for (let i = 0; i < input.length; i++) {
if (input[i].value == "") {
valid = false;
break;
}
}
for (let i = 0; i < select.length; i++) {
if (select[i].value == "") {
valid = false;
break;
}
}
} else if (radio[0].name == "phnum" && radio[0].checked) {
if (input[0].value == "" || input[1].value == "") {
valid = false;
}
} else if (radio[1].name == "phnum" && radio[1].checked) {
if (input[0].value == "" || input[1].value == "" || input[2].value == "") {
valid = false;
}
}
if (valid) {
document.getElementById("next").className = "prevNext";
}
}
<span id="radio">
<label for="phnum1" class="radio-container">
<input type="radio" name="phnum" id="phnum1" value="1" onchange="displayPhone(this);">1 Number
<span class="radio"></span>
</label>
<label for="phnum2" class="radio-container">
<input type="radio" name="phnum" id="phnum2" value="2" onchange="displayPhone(this);">2 Numbers
<span class="radio"></span>
</label>
<label for="phnum3" class="radio-container">
<input type="radio" name="phnum" id="phnum3" value="3" onchange="displayPhone(this);">3 Numbers
<span class="radio"></span>
</label>
</span>
</p><br>
<p id="ph1" class="disable">
<label for="phone-number1">Add a Phone Number: </label><input type="tel" name="phone-number1" id="phone-number1" class="input" placeholder="Add A Phone Number" required oninput="validate();">
</p>
<p id="ph2" class="disable">
<label for="phone-number2">Add a Phone Number: </label><input type="tel" name="phone-number2" id="phone-number2" class="input" placeholder="Add A Phone Number" required onchange="validate();">
</p>
<p id="ph3" class="disable">
<label for="phone-number3">Add a Phone Number: </label><input type="tel" name="phone-number3" id="phone-number3" class="input" placeholder="Add A Phone Number" required onchange="validate();">
</p>
that handles the input added by the user to make a button clickable if all necessary data is added. the problem is when i delete inside the input with back arrow key(the one above enter) the button remains active even if the condition for its activation no longer applies.
thank you guys for your time and help i really do appreciate it. :D
One thing I see - you're setting the class name if valid == true via document.getElementById("next").className = "prevNext";.
But nowhere are you removing that class name if valid == false.
That's probably why you aren't seeing the button disappear when you empty out the fields (if I understand your problem correctly).
if (!valid) { document.getElementById("next").className = ""; } is a quick and dirty way to get what you need.
i have some code that works for a password form where the user is filling out their details and then 2 of the boxes only work or become typable if they enter a number/age greater than that specified. i now want to take it one step further and make it obvious to the user that those boxes are only editable certain times by colouring them in a different colour. for some reason though the new code within the JS is not working.
code is below:
<div class="container">
<div class="jumbotron" id="firstform">
<h1>Sign up page</h1>
<form id="myform">
<label>Username </label> <input type="text" name="uname" id="uname" data-placement="bottom" title="" data-original-title="Username must be unique" class="mytooltip"><br>
<div class="pwordCheck">
<label>Password </label> <input type="password" id="pword" data-placement="bottom" title="" onkeyup="passwordValidation(); return false;" data-original-title="Password must be more than 6 characters long" class="mytooltip"><br>
<label>Confirm Password </label> <input type="password" id="confpword" onkeyup="passwordValidation(); return false;" data-placement="bottom" title="" data-original-title="Passwords must match" class="mytooltip">
<span id="themessage" class="themessage"></span><br>
</div>
<label>Email </label> <input type="email" id="e-mail"><br>
<label>Age </label> <input type="number" id="age" oninput="ifOfAge(); return false;"><br>
<label>Can you drive? </label> <input type="text" id="drive" disabled><br>
<label>What is your occupation? </label> <input type="text" id="occupation" disabled><br>
<input type="submit" value="Submit" onclick="usernameAlreadyExists(); return false;">
</form>
</div>
</div>
css:
input#drive{
background-color: #999;
}
input#occupation{
background-color: #999;
}
js:
function ifOfAge() {
var age = document.getElementById("age");
var drive = document.getElementById("drive");
var occupation = document.getElementById("occupation");
var white = "#fff";
if (age.value >= 21) {
drive.disabled = false;
occupation.disabled = false;
} else if (age.value >= 16) {
drive.disabled = false;
occupation.style.backgroundColor = white;
} else {
drive.disabled = true;
occupation.disabled = true;
drive.style.backgroundColor = white;
occupation.style.backgroundColor = white;
}
}
Color must be enclosed within quotes. Like below. Wherever you have used white surround it with quotes
drive.style.backgroundColor = "white";
you can make change color for disabled input like this.
EDIT
function ifOfAge() {
var age = document.getElementById("age");
var drive = document.getElementById("drive");
var occupation = document.getElementById("occupation");
var white = "#fff";
if (age.value >= 21) {
drive.disabled = false;
occupation.disabled = false;
} else if (age.value >= 16) {
drive.disabled = false;
occupation.style.backgroundColor = white;
} else {
drive.disabled = true;
occupation.disabled = true;
drive.style.backgroundColor = "#999";
occupation.style.backgroundColor = "#999";
}
}
You can make it more nice if you used jQuery and plugin jQuery Validation or even more nice with this one.