Javascript 如何使用javascript检查文本框是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3502354/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a textbox is empty using javascript
提问by user222585
I have a jsp page with some TextBoxes. Now I want to fill them with some information and click the submit button. But I need to check whether this TextBox is empty or not.
我有一个带有一些文本框的 jsp 页面。现在我想用一些信息填充它们并单击提交按钮。但我需要检查这个 TextBox 是否为空。
How can I do this?
我怎样才能做到这一点?
回答by sweets-BlingBling
Using regexp: \S will match non whitespace character:anything but not a space, tab or new line. If your string has a single character which is not a space, tab or new line, then it's not empty. Therefore you just need to search for one character: \S
使用正则表达式:\S 将匹配非空白字符:除空格、制表符或换行符以外的任何内容。如果您的字符串有一个不是空格、制表符或新行的字符,那么它就不是空的。因此,您只需要搜索一个字符:\S
JavaScript:
JavaScript:
function checkvalue() { 
    var mystring = document.getElementById('myString').value; 
    if(!mystring.match(/\S/)) {
        alert ('Empty value is not allowed');
        return false;
    } else {
        alert("correct input");
        return true;
    }
}
HTML:
HTML:
<form onsubmit="return checkvalue(this)">
    <input name="myString" type="text" value='' id="myString">
    <input type="submit" value="check value" />
</form>
回答by mplungjan
Canonical without using frameworks with added trim prototype for older browsers
Canonical 不使用为旧浏览器添加修剪原型的框架
<html>
<head>
<script type="text/javascript">
// add trim to older IEs
if (!String.trim) {
  String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g, "");};
}
window.onload=function() { // onobtrusively adding the submit handler
  document.getElementById("form1").onsubmit=function() { // needs an ID
    var val = this.textField1.value; // 'this' is the form 
    if (val==null || val.trim()=="") { 
      alert('Please enter something');
      this.textField1.focus();
      return false; // cancel submission
    }
    return true; // allow submit
  }
}
</script>
</head>
<body>
<form id="form1">
  <input type="text" name="textField1" value="" /><br/>
  <input type="submit" />
</form>
</body>
</html>
Here is the inline version, although not recommended I show it here in case you need to add validation without being able to refactor the code
这是内联版本,虽然不推荐我在这里展示它以防您需要添加验证而无法重构代码
function validate(theForm) { // passing the form object
  var val = theForm.textField1.value;
  if (val==null || val.trim()=="") { 
    alert('Please enter something');
    theForm.textField1.focus();
    return false; // cancel submission
  }
  return true; // allow submit
}
passing the form object in (this)
在 (this) 中传递表单对象
<form onsubmit="return validate(this)">
  <input type="text" name="textField1" value="" /><br/>
  <input type="submit" />
</form>
回答by Rubyist
Using this JavaScript will help you a lot. Some explanations are given within the code.
使用这个 JavaScript 会对你有很大帮助。代码中给出了一些解释。
<script type="text/javascript">
    <!-- 
        function Blank_TextField_Validator()
        {
        // Check whether the value of the element 
        // text_name from the form named text_form is null
        if (!text_form.text_name.value)
        {
          // If it is display and alert box
           alert("Please fill in the text field.");
          // Place the cursor on the field for revision
           text_form.text_name.focus();
          // return false to stop further processing
           return (false);
        }
        // If text_name is not null continue processing
        return (true);
        }
        -->
</script>
<form name="text_form" method="get" action="#" 
    onsubmit="return Blank_TextField_Validator()">
    <input type="text" name="text_name" >
    <input type="submit" value="Submit">
</form>
回答by Muhammad Azeem
You can also check it using jQuery.. It's quite easy:
您也可以使用 jQuery 来检查它.. 很简单:
<html>
    <head>
        <title>jQuery: Check if Textbox is empty</title>
        <script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
    </head>
    <body>
        <form name="form1" method="post" action="">
            <label for="city">City:</label>
            <input type="text" name="city" id="city">
        </form>
        <button id="check">Check</button>
        <script type="text/javascript">
             $('#check').click(function () {
                 if ($('#city').val() == '') {
                     alert('Empty!!!');
                 } else {
                     alert('Contains: ' + $('#city').val());
                 }
             });                
        </script>
    </body>
</html>
回答by Alex
Whatever method you choose is not freeing you from performing the same validation on at the back end.
无论您选择哪种方法,都不会让您免于在后端执行相同的验证。
回答by PRATEEK GHOSH
The most simple way to do it without using javascript is using required=""
不使用 javascript 的最简单方法是使用required=""
<input type="text" ID="txtName"  Width="165px" required=""/>
回答by Ravindra Bohra
<pre><form name="myform"  method="post" enctype="multipart/form-data">
    <input type="text"   id="name"   name="name" /> 
<input type="submit"/>
</form></pre>
<script language="JavaScript" type="text/javascript">
 var frmvalidator  = new Validator("myform");
    frmvalidator.EnableFocusOnError(false); 
    frmvalidator.EnableMsgsTogether(); 
    frmvalidator.addValidation("name","req","Plese Enter Name"); 
</script>
Note: before using the code above you have to add the gen_validatorv31.jsfile.
注意:在使用上面的代码之前,您必须添加gen_validatorv31.js文件。

