Reputation: 3
I've looked at some of the answers here but for some reason, I can't get this to work. I want the user to grade something and if they input nothing in the required field and press "Grade", I want for it to alert something.
function Script() {
var G = document.getElementById("gradevalue").value
if (G == null || G == undefined) {
window.alert("Please input a grade");
}
}
<label id="grade">|Please grade on a scale from 1 to 10 (10 is the best!)
<input id="gradevalue" type="text"; size="2"; maxlength="2">
</label>
<input type="button" value="GRADE!" id="nota" onclick="Script()">
I'm very new at this, so please don't be too harsh.
Upvotes: 0
Views: 77
Reputation: 4622
I think, you can simply check it like:
if (!Number(G)) {
window.alert("Please input a grade");
}
this is going to be true
if G
is null
, undefined
, ''
, 0
, false
and NaN
and any strings that are not converted to numbers.
function CheckGrade () {
var G = document.getElementById("gradevalue").value;
if(!Number(G)) {
window.alert("Please input a grade");
} else {
//your code here, maybe some othe validation logic
}
}
<label id="grade">|Please grade on a scale from 1 to 10 (10 is the best!)
<input id="gradevalue" type="number" min="1" max="10"/>
</label>
<input type="button" value="GRADE!" id="nota" onclick="CheckGrade()">
UPDATE Added a code sample and minor mistakes.
Upvotes: 2
Reputation: 13
You are also must there, in JavaScript you can just check if the variable has a value assigned to it, if it doesn't then the bool expression will be false. I have done a quick CodePen with the working code https://codepen.io/robdavis/pen/bRVxdm
function Script() {
var g = document.getElementById("gradevalue").value
if (!g) {
window.alert("Please enter a Grade");
}
}
Upvotes: 0
Reputation: 18279
Checking !G || G == 0
seems to do the job:
function Script() {
var G = document.getElementById("gradevalue").value
if(!G || G == 0) {
window.alert("Please input a grade");
}
}
<label id="grade">|Please grade on a scale from 1 to 10 (10 is the best!)
<input id="gradevalue" type="text"; size="2"; maxlength="2">
</label>
<input type="button" value="GRADE!" id="nota" onclick="Script()">
Note that you may also want to check for > 11 values:
if (!G) {
window.alert("Please input a grade");
} else if(G == 0 || G > 10) {
window.alert("Please input a grade between 1 and 10");
}
Upvotes: 1