我有一个带有textarea字段的表单。我喜欢定义允许150个单词的单词数量。
如何使用javascript实现此目的?
<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>
我有以下似乎错误的代码。
<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>
答案 0 :(得分:0)
只需在" "
上拆分文字,然后按照这样的方式计算文字:
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(' ');
会像这样返回Array
:
["Detail", "text", "should", "be", "a", "maximum", "of", "150", "words"];
它的长度是9
,这是字符串中单词的数量。