Javascript 定义允许在文本区域字段中提交的字数
我有一个带有textarea字段的表单。我喜欢定义150个单词的词数 如何使用javascript实现这一点Javascript 定义允许在文本区域字段中提交的字数,javascript,textarea,word,Javascript,Textarea,Word,我有一个带有textarea字段的表单。我喜欢定义150个单词的词数 如何使用javascript实现这一点 <form name="main" action="" method="post"> <label> <span class="legend">Details: </span>(Enter a maximum of 150 words) <textarea name="description">
<form name="main" action="" method="post">
<label>
<span class="legend">Details: </span>(Enter a maximum of 150 words)
<textarea name="description">
</textarea>
</label>
</fieldset>
<input type="submit" class="search" value="Submit">
</form>
详细信息:(最多输入150字)
我有以下代码,似乎是错误的
<script type="text/javascript">
function validate() {
if (document.forms['main'].detail.value.length > 150)
{
document.forms['main'].detail.focus();
alert("Detail text should be a maximum of 150 characters");
return false;
}
if (document.forms['main'].faultType[1].checked==true && (document.forms['main'].detail.value).length == 0)
{
document.forms['main'].detail.focus();
alert("Enter some text that describes the fault");
return false;
}
return true;
}
</script>
函数验证(){
if(document.forms['main'].detail.value.length>150)
{
document.forms['main'].detail.focus();
警报(“详细文本最多应为150个字符”);
返回false;
}
if(document.forms['main'].faultType[1]。选中==true&(document.forms['main'].detail.value)。长度==0)
{
document.forms['main'].detail.focus();
警报(“输入一些描述故障的文本”);
返回false;
}
返回true;
}
只需在“
上拆分文本,并按此方式计算单词数:
function validate() {
var main = document.forms['main'];
if (main.detail.value.split(' ').length > 150){
main.detail.focus();
alert("Detail text should be a maximum of 150 words");
return false;
}
if (main.faultType[1].checked==true && main.detail.value.length == 0) {
main.detail.focus();
alert("Enter some text that describes the fault");
return false;
}
return true;
}
例如:
"Detail text should be a maximum of 150 words".split(' ');
将返回如下所示的数组
:
["Detail", "text", "should", "be", "a", "maximum", "of", "150", "words"];
它的长度是
9
,即字符串中的字数。150个字?编写代码是为了检查字符长度。重复:您正在查找类似myTextArea.text.split('').length的内容以查找字数。您需要计算空格数,而不是字符数。