开发者

checking whether textfield contains letters in javascript

开发者 https://www.devze.com 2023-01-30 19:43 出处:网络
I am new at Javascript and I wanted to know if there is a way to check if textfield input contains anything other than numbers.

I am new at Javascript and I wanted to know if there is a way to check if textfield input contains anything other than numbers.

I know how to do that in Java, but Javascript is a to开发者_运维知识库tally different thing to me.


Yup - just standard regex on the string:

var str = 'mystring 123';
if(str.match(/[^0-9]/)) { ... }

If you need to know how to get the string from the element:

var str = document.getElementById('myId').value;


You can use isNaN() to check if the input is a number or not.

HTML:

<textarea id="inputText"></textarea>
<input type="button" onClick="checkInput();">

JavaScript:

function checkInput()
{
  var textCheck = document.getElementById("inputText").value;
  if(isNaN(textCheck))
  {
    document.write("contains letters");
  }
  else
  {
    document.write("only numbers");
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消