0

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

https://i.sstatic.net/jA35X.jpg

1
  • 1
    If you want someone to do something with your code, post it as code not as a screenshot of code. Commented Aug 4, 2015 at 16:30

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

if I enter XXX in input box it returns "Valid number"
0

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

@hopkins-matt Yea.. Don't wanna make it hard for Max.
Doesn' validate if it's number or not
@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.
This will not work if month is 12, which is a valid month
@Keerthi Oops. Fix it. Thx.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.