简体   繁体   中英

Nesting If Else Statements in Javascript

I'm beginning to create a web app where a user will select their age, gender and a few other things, which will then return a piece of information specific to their answers.

I've always neglected learning Javascript properly, so it's something of a learning experience. The most obvious way to me seemed to be with if/else statements. However, I am wary that this would lead to very messy code, so I'm wondering whether I'm way off the mark in pursuing this project with just plain Javascript or if else statements.

I've began the task with JS, but it's tripping up somewhere. It correctly selects the gender, then the age, but when I try to display information based on both selections, it gets it incorrect.

 /* If you're feeling fancy you can add interactivity to your site with Javascript */ // prints "hi" in the browser's dev tools console console.log('hi'); function gender() { var userGender = document.getElementById("genderInput").value; console.log('Gender selected as ' + userGender); } function age() { var userAge = document.getElementById("ageInput").value; console.log('Age selected as ' + userAge); } function summary() { if (userGender = 'Male') { if (userAge = 'u35') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge = '36-45') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge = '46-55') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge = '56-65') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge = 'o65') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } } else if (userGender = 'Female') { if (userAge = 'u35') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge = '36-45') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge = '46-55') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge = '56-65') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge = 'o65') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } } else { console.log('nothing selected'); } } 
 <!DOCTYPE html> <html lang="en"> <head> <title>Hello!</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- import the webpage's stylesheet --> <link rel="stylesheet" href="/style.css"> <!-- import the webpage's javascript file --> <script src="/script.js" defer></script> </head> <body> <h1>Hi there!</h1> <h3> Gender </h3> <form id="genderApp" onsubmit="return false;"> <select id="genderInput" name="genderSelect"> <option value="Male">Male</option> <option value="Female">Female</option> </select> <input type="submit" onclick="gender()"> </form> <h3> Age </h3> <form id="ageApp" onsubmit="return false;"> <select id="ageInput" name="ageSelect"> <option value="u35">Under 35</option> <option value="36-45">36-45</option> <option value="46-55">46-55</option> <option value="56-65">56-65</option> <option value="o65">Over 65</option> </select> <input type="submit" onclick="age()"> </form> <button onclick="summary()"> Summary </button> <!-- include the Glitch button to show what the webpage is about and to make it easier for folks to view source and remix --> <div class="glitchButton" style="position:fixed;top:20px;right:20px;"></div> <script src="https://button.glitch.me/button.js"></script> </body> </html> 

Appreciate any help, whether it's pointing out the error in this attempt or calling me a fool for attempting this with this method!

Why you code isn't working is addressed in the comments, you are using = instead of === . One is assignment operator the other performs equality checks.

I'm wondering whether I'm way off the mark in pursuing this project with just plain Javascript or if else statements

You can use an array of objects to declare responses and their constraints instead of if/else blocks.

 const responses = [ { age: { min: 5, max: 12 }, gender: 'male', func: function() { console.log('is a male between 5 - 12') } }, { age: { min: 60, max: 65 }, gender: 'female', func: function() { console.log('is a female between 60 - 65') } } ] const main = (age, gender) => { // find a response that matches all constraints const response = responses.find(response => { return response.gender === gender && response.age.min <= age && response.age.max >= age }) if (!response) { throw 'No response found for this age range/gender' } response.func() } main(8, 'male') main(60, 'female') 

This can be made even more DRY ; The response func message can be computed by the gender and age.min / age.max props but that's besides the question.

Just create a single function and on click of summary get the gender and the age range

 console.log('hi'); function summary() { var userGender = document.getElementById("genderInput").value; var userAge = document.getElementById("ageInput").value; console.log(`The user is ${userGender} and ${userAge} years old`) } 
 <h1>Hi there!</h1> <h3> Gender </h3> <form id="genderApp" onsubmit="return false;"> <select id="genderInput" name="genderSelect"> <option value="Male">Male</option> <option value="Female">Female</option> </select> <input type="submit" onclick="gender()"> </form> <h3> Age </h3> <form id="ageApp" onsubmit="return false;"> <select id="ageInput" name="ageSelect"> <option value="u35">Under 35</option> <option value="36-45">36-45</option> <option value="46-55">46-55</option> <option value="56-65">56-65</option> <option value="o65">Over 65</option> </select> <input type="submit" onclick="age()"> </form> <button onclick="summary()"> Summary </button> <!-- include the Glitch button to show what the webpage is about and to make it easier for folks to view source and remix --> <div class="glitchButton" style="position:fixed;top:20px;right:20px;"></div> 

You are making two mistakes here:

  • First you using assignment operator = for if stataments. You should comparison operator == or === but in this case you don't need to do that because all the block have same console.log()
  • The variable userGender and userAge should be declared in global scope

 /* If you're feeling fancy you can add interactivity to your site with Javascript */ // prints "hi" in the browser's dev tools console console.log('hi'); var userGender; var userAge; function gender() { userGender = document.getElementById("genderInput").value; console.log('Gender selected as ' + userGender); } function age() { userAge = document.getElementById("ageInput").value; console.log('Age selected as ' + userAge); } function summary() { console.log(`The user is ${userGender} and ${userAge} years old`); } 
 <!DOCTYPE html> <html lang="en"> <head> <title>Hello!</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- import the webpage's stylesheet --> <link rel="stylesheet" href="/style.css"> <!-- import the webpage's javascript file --> <script src="/script.js" defer></script> </head> <body> <h1>Hi there!</h1> <h3> Gender </h3> <form id="genderApp" onsubmit="return false;"> <select id="genderInput" name="genderSelect"> <option value="Male">Male</option> <option value="Female">Female</option> </select> <input type="submit" onclick="gender()"> </form> <h3> Age </h3> <form id="ageApp" onsubmit="return false;"> <select id="ageInput" name="ageSelect"> <option value="u35">Under 35</option> <option value="36-45">36-45</option> <option value="46-55">46-55</option> <option value="56-65">56-65</option> <option value="o65">Over 65</option> </select> <input type="submit" onclick="age()"> </form> <button onclick="summary()"> Summary </button> <!-- include the Glitch button to show what the webpage is about and to make it easier for folks to view source and remix --> <div class="glitchButton" style="position:fixed;top:20px;right:20px;"></div> <script src="https://button.glitch.me/button.js"></script> </body> </html> 

I just corrected the mistakes without improving the code.

== should be used for comparing values and = for assignment

And variable should be global if you want to access it globally else get those variables initialized in function itself.

 /* If you're feeling fancy you can add interactivity to your site with Javascript */ // prints "hi" in the browser's dev tools console console.log('hi'); function gender() { var userGender = document.getElementById("genderInput").value; console.log('Gender selected as ' + userGender); } function age() { var userAge = document.getElementById("ageInput").value; console.log('Age selected as ' + userAge); } function summary() { var userGender = document.getElementById("genderInput").value; var userAge = document.getElementById("ageInput").value; if (userGender == 'Male') { if (userAge == 'u35') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge == '36-45') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge == '46-55') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge == '56-65') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge == 'o65') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } } else if (userGender == 'Female') { if (userAge == 'u35') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge == '36-45') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge == '46-55') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge == '56-65') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } else if (userAge == 'o65') { console.log('The user is ' + userGender + 'and ' + userAge + ' years old'); } } else { console.log('nothing selected'); } } 
 <!DOCTYPE html> <html lang="en"> <head> <title>Hello!</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- import the webpage's stylesheet --> <link rel="stylesheet" href="/style.css"> <!-- import the webpage's javascript file --> <script src="/script.js" defer></script> </head> <body> <h1>Hi there!</h1> <h3> Gender </h3> <form id="genderApp" onsubmit="return false;"> <select id="genderInput" name="genderSelect"> <option value="Male">Male</option> <option value="Female">Female</option> </select> <input type="submit" onclick="gender()"> </form> <h3> Age </h3> <form id="ageApp" onsubmit="return false;"> <select id="ageInput" name="ageSelect"> <option value="u35">Under 35</option> <option value="36-45">36-45</option> <option value="46-55">46-55</option> <option value="56-65">56-65</option> <option value="o65">Over 65</option> </select> <input type="submit" onclick="age()"> </form> <button onclick="summary()"> Summary </button> <!-- include the Glitch button to show what the webpage is about and to make it easier for folks to view source and remix --> <div class="glitchButton" style="position:fixed;top:20px;right:20px;"></div> <script src="https://button.glitch.me/button.js"></script> </body> </html> 

Other answers have told you your mistakes.

Here is my version intended to educate on better practices

  • using unobtrusive event listeners
  • using an object to match proper text to values

 var ages = { u35: "under 35", "36-45": "between 36 and 35", "46-55": "between 46 and 55", "56-65": "between 56 and 65", "o65": "over 65" } window.addEventListener("load", function() { document.getElementById("genderInput").addEventListener("change", function() { var userGender = this.value; console.log('Gender selected as ' + userGender); }); document.getElementById("ageInput").addEventListener("change", function() { var userAge = this.value; console.log('Age selected as ' + userAge); }); document.getElementById("summary").addEventListener("click", function() { var userGender = document.getElementById("genderInput").value; var userAge = document.getElementById("ageInput").value; if (!userGender && !userAge) { console.log('nothing selected'); return; } var text = []; if (userGender) text.push(userGender); if (userAge) text.push(ages[userAge] + ' years old'); console.log('The user is ' + text.join(" and ")); }) }); 
 <h1>Hi there!</h1> <form> <h3>Gender</h3> <select id="genderInput" name="genderSelect"> <option value="">Please select</option> <option value="Male">Male</option> <option value="Female">Female</option> <option value="Other">Other</option> </select> <h3>Age</h3> <select id="ageInput" name="ageSelect"> <option value="">Please select</option> <option value="u35">Under 35</option> <option value="36-45">36-45</option> <option value="46-55">46-55</option> <option value="56-65">56-65</option> <option value="o65">Over 65</option> </select> <button id="summary" type="button">Summary</button> </form> 

Using es6 template strings we can build a smart console log based on criteria passed to the handleUser method

 const handleUser = filter => { const age = filter === 'gender' ? null : document.querySelector('#ageInput').value const gender = filter === 'age' ? null : document.querySelector('#genderInput').value if (!gender && !age) return alert('please complete the form') // build log frorm age and gender data console.log(`User is ${!!gender ? gender : ''}${!!gender && !!age ? ' and ' : ''}${!!age ? `aged ${age}` : ''}`) // Use switch to handle your age ranges (more readable imho than if-else etc) // assumig eventually you are going to want to add more logic based on age... switch (age) { case 'u35': break; case '36-45': break; case '46-55': break; case '56-65': break; case 'o65': break; default: break; } } 
 <h1>Hi there!</h1> <h3> Gender </h3> <form id="genderApp" onsubmit="return false;"> <select id="genderInput" name="genderSelect"> <option></option> <option value="Male">Male</option> <option value="Female">Female</option> </select> <input type="submit" onclick="handleUser('gender')"> </form> <h3> Age </h3> <form id="ageApp" onsubmit="return false;"> <select id="ageInput" name="ageSelect"> <option></option> <option value="u35">Under 35</option> <option value="36-45">36-45</option> <option value="46-55">46-55</option> <option value="56-65">56-65</option> <option value="o65">Over 65</option> </select> <input type="submit" onclick="handleUser('age')"> </form> <button onclick="handleUser()"> Summary </button> </br> </br> </br> </br> </br> </br> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM