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
-
1If you want someone to do something with your code, post it as code not as a screenshot of code.martynasma– martynasma2015年08月04日 16:30:28 +00:00Commented Aug 4, 2015 at 16:30
2 Answers 2
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
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>