user3760941 user3760941 - 9 months ago 23
CSS Question

Null values & logical operators not working

I am trying to figure out why if I enter null values, the alert still appears when it shouldn’t. the argument states that all values must not be null otherwise the function should end.

Does anyone have any ideas? thank you!



@charset "UTF-8";
/* CSS Document */

body{
height:1000px;
width:100%;
background:#fff;
margin:0;
}

.divider{
width:100%;
height:auto;
background:#CCC;
display:block;
margin:10px;
}

h2{
font-size:16px;
display:block;
}
#confirm-paragraph{}
#global-variable-paragraph{}
#user-input{}
#expressions{}
#elephant-paragraph{}
#method-1{}
#method-2{}
#ml{}
#litres{}
#conditional-operator{}
#cast-1{}
#cast-2{}

<!-- Checklist: Obtain user input and store it in variables -->
<!-- Report variable text to the client window -->
<!-- Prompt -->
<section class="divider">
<h2>User Input Variables Example</h2>
<button onclick="nameFunction()">Click Me</button>
<p id="user-input">This text should change after clicking the button.</p>
<p style="color:red; font-weight:bold">NOT WORKING Version3!!!!!!!!</p>
<p>Should not alert if null values are present - null values are present by just clicking OK when entering nothing. All values should not be null in order for the alert to appear</p>
<script>
function nameFunction() {
var yourforename = prompt("What is your first name?");
var yoursurname = prompt("What is your last name?");
var yourage = prompt("What is your age?");

if (yourforename != null && yoursurname != null && yourage != null) {
alert("Hello " + yourforename + " " + yoursurname + ". You are " + yourage + " years old.");
}
}
</script>
</section>




Answer Source

I'm guessing it is a confusion over the return value. If you type nothing in the prompt, then the empty string ("") is returned. However, if you click the cancel button, then null is returned. Your code is only checking for not null. "" is not equal to null, so the pass checks. A quick fix could be to change

if (yourforename != null && yoursurname != null && yourage != null) {
    alert("Hello " + yourforename + " " + yoursurname + ". You are " + yourage + " years old.");
    }

to

if (yourforename && yoursurname && yourage) {
    alert("Hello " + yourforename + " " + yoursurname + ". You are " + yourage + " years old.");
    }