checking whether textfield contains letters in javascript

好久不见. 提交于 2019-12-01 11:59:20

问题


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 totally different thing to me.


回答1:


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;



回答2:


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");
  }
}


来源:https://stackoverflow.com/questions/4466398/checking-whether-textfield-contains-letters-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!