-2

I am fairly new with javascript and I need a script to obtain the value of an input text and check that value if it is equal to 0 (zero). If it does then I need an alert message notifying me that the text input is 0. Thanks.

<input id="txtVal" type="text" name="txtVal" value="0" maxlength="10">  
Saic Siquot
  • 6,513
  • 5
  • 34
  • 56
Lucky
  • 9
  • 1
  • 1
    Welcome to StackOverflow! Please be sure to read our [ask] page to help you formulate a great question. You are much more likely to get a good answer from the community if you put some effort into your question. – blurfus Apr 14 '15 at 22:48
  • 1
    Take it step by step. Start with: `document.getElementById("txtVal").value` ... – ROMANIA_engineer Apr 14 '15 at 22:49
  • Thanks for your instant replies. ok I use the getElementById then how I check that value if it is equal to 0? Thanks – Lucky Apr 14 '15 at 22:55
  • `var value = document.getElementById("txtVal").value if(value == 0 ){ alert("You choose 0") }` – Paul Fitzgerald Apr 14 '15 at 23:01

1 Answers1

0

The short answer:

if(txVal.value==0) alert('Please enter a number.');

Is not always the best answer:

var v=document.getElementById('txtVal');
v=parseInt(v,10);
if(v<=0) alert('Please enter a positive integer.');

Of course that probably not the best answer either but it does fix a couple of common mistakes.

  • Although you can refer to an element by using its id as a variable name its not recomended.
  • The value property of an input (ie txtVal.value) is a string (even if it contains only digits) so if you try to compare it to a number you may get unexpected results. In this case you are comparing it to 0 so problems are less likely but if you ever change your code to compare to another number you will probably run into problems, so its best to make it into an actual number before you do anything with it.

If you want to allow decimals use parseFloat instead.

Bob
  • 523
  • 4
  • 11