Textarea验证不起作用Javascript [英] Textarea validation does not work Javascript

查看:73
本文介绍了Textarea验证不起作用Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码示例:
HTML:

here is the code sample: HTML:

 <form id="information" name="information" action="#" method="post"> 
 <textarea name="text" rows="10" cols="10"> 
 </textarea> 
 <input type="submit" value="submit"/> 
 </form> 

Javascript:

Javascript:

 window.onload=init;

 function init(){
 document.getElementById('information').onsubmit=validateForm;
 }

 function validateForm(){ 
 var text= document.information.text.value; 
 if(text==""){ 
 alert('text area cannot be empty');
 return false;
 } 
 }

它不起作用......

it does not work...

推荐答案

textarea里面有一个回车符(以及一个空格),所以你的情况永远不会成真。因此,将其更改为:

The textarea has a carriage return in it (and a space), so your condition is never true. So change it to:

<textarea name="text" rows="10" cols="10"></textarea> 

但是你可能想要进一步阻止用户输入空响应(意味着除了白色空间)。或者您可能只想删除前导和尾随空格。如果是这样,你可以这样做:

However you may want to go further and stop the user entering an "empty" response (meaning nothing but white-space). Or you may just want to remove leading and trailing white-space. If so you can do this:

text = text.trim();

现在 trim() 我认为相对较新(Firefox将其列为3.5中的新功能)。更向后兼容的版本是:

Now trim() I believe is relatively new (Firefox lists it as new in 3.5). A more backwards compatible version is:

text = text..replace(/^\s\s*/, '').replace(/\s\s*$/, '');

然后测试它是否为空。

更快的JavaScript修剪对各种白色空间修剪替代方案进行了很好的分析。例如,上面的一个正则表达式可以完成:

Faster JavaScript Trim has a good analysis on various white-space trimming alternatives. For instance the above can be done with one regex:

text = text..replace(/^\s+|\s+$/g, '');

但是


这种常见的方法是
,这是目前
JavaScript库中最常用的方法。只有当使用
短字符串(不包括
前导或尾随空格)时,
通常是最快的实现
。这个
次要优势部分归因于它触发的
初始字符歧视
优化。虽然这个
是一个相对不错的表演者,但是当使用更长的字符串时,它比
以上的三种方法慢了
,因为顶级替换
会阻止一个数字优化
,否则可以开始。

This commonly thought up approach is easily the most frequently used in JavaScript libraries today. It is generally the fastest implementation of the bunch only when working with short strings which don't include leading or trailing whitespace. This minor advantage is due in part to the initial-character discrimination optimization it triggers. While this is a relatively decent performer, it's slower than the three methods above when working with longer strings, because the top-level alternation prevents a number of optimizations which could otherwise kick in.

这篇关于Textarea验证不起作用Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆