So, I am writing a piece of code which checks the month of a number after it has been entered into a textbox, it checks to see if it is a valid number of a month (1-12) and if it is not displays an error message. I get the basic principle of it but i dont get how to run the checking after pressing the button, if you want to help that would be great ! And try and base it om what i already have :p
2 Answers
function myFunction(){
number = document.getElementById('myText').value;
if(isNaN(number)){
alert('Not a valid month');
}else {
if( number > 0 && number <= 12){
alert('valid month');
}else{
alert('Not a valid month');
}
}
}
Month no: <input type="text" id="myText" />
<button onclick="myFunction();">Go</button>
1 Comment
Zlatko Vujicic
if I enter XXX in input box it returns "Valid number"
The original, more complete way is:
function myFunction() {
var month = parseInt(document.getElementById('myText').value);
if (typeof month === 'number' && month <= 12 && month > 0) {
alert('yes! valid month! ');
} else {
alert('invalid month! ');
}
}
document.getElementById('myText').value should be a string, and parseInt() convert it to a number.
Update: Use the complete solution, or may cause lots of problems.
However, If you don't want to make it too complicate, just use below code.
function myFunction() {
var month = document.getElementById('myText').value;
if (month <= 12 && month > 0) {
alert('yes! valid month! ');
} else {
alert('invalid month! ');
}
}
<html>
<body>
<title>Month Checker 3000</title>
<h1>Month Checker</h1>
Month Number:
<input type="text" id="myText" />
<button onclick="myFunction()">Go</button>
</body>
</html>
5 Comments
iplus26
@hopkins-matt Yea.. Don't wanna make it hard for Max.
Zlatko Vujicic
Doesn' validate if it's number or not
iplus26
@ZlatkoVujicic Sorry, I validated it for the first time, and then I deleted it to simplify the code, and I updated the answer to add it back.
Keerthi
This will not work if month is 12, which is a valid month
iplus26
@Keerthi Oops. Fix it. Thx.