我创建了一个表单供用户提交摘要。但在提交时我需要检查天气他们已经添加了超过250个单词。我只需要250个单词。怎么做?
我尝试了一些JavaScript,但它仅适用于250个字符。
这是我的代码
function maxlength(element, maxvalue)
{
var q = eval("document.upload."+element+".value.length");
var r = q - maxvalue;
var msg = "Sorry, you have input "+q+" characters into the "+
"text area box you just completed. It can return no more than "+
maxvalue+" words to be processed. Please abbreviate "+
"your text by at least "+r+" words";
if (q > maxvalue) alert(msg);
}
我的textarea是:
<tr>
<td><label>Abstract Details</label> </td>
<td><label>Please enter data, at most 250 words:</label>
<br/><textarea rows="6" cols="80"name="box_name" onChange="maxlength('box_name', 250)" style="width: 257px; height: 131px;"> </textarea></td>
</tr>
<tr>
如何限制250个单词。
提前致谢
答案 0 :(得分:8)
要防止在textarea中超过250个字符时提交表单,请将id="box_id"
添加到您的textarea并将此事件添加到表单元素:
onsubmit="return maxlength(getElementById('box_id'), 250);
现在,在您的函数中,将此值拆分多个空格:
function maxlength(element, maxvalue){
var q = element.value.split(/[\s]+/).length;
if(q > maxvalue){
var r = q - maxvalue;
alert("Sorry, you have input "+q+" words into the "+
"text area box you just completed. It can return no more than "+
maxvalue+" words to be processed. Please abbreviate "+
"your text by at least "+r+" words");
return false;
}
}
要利用新的HTML属性,您还可以将“pattern”属性添加到textarea,并将正则表达式限制输入设置为250个单词:
<textarea rows="6" cols="80"name="box_name" onChange="maxlength(this, 250)" style="width: 257px; height: 131px;"
pattern="^(?:\b\w+\b[\s\r\n]*){1,250}$">
</textarea>
这个正则表达式模式来自以下SO线程,它接触250个单词的类似问题:Limit the number of words in a response with a regular expression
答案 1 :(得分:1)
如果需要250个字符,可以将maxlength属性设置为250
如果你想要250个单词:
function maxlength(obj,wordLen){
var len = obj.value.split(/[\s]+/);
if(len.length > wordLen){
alert("You cannot put more than "+wordLen+" words in this text area.");
}
}
功能调用:
onChange="maxlength(this, 250)"
<强> Working Demo 强>
答案 2 :(得分:1)
使用它:
function maxlength(element, maxvalue)
{
var value = $(elment).val();
var words = value.split(' ');
var msg = 'Sorry, you have input ' + words.length + ' words into the ' +
'text area you just completed. It can return no more than ' +
maxvalue + ' words to be processed. Please abbreviate ' +
'your text by at least ' + (words.length - maxvalue) + ' words';
if (words.length > maxvalue) {
alert(msg);
}
}
答案 3 :(得分:0)
如果您要限制eval("document.upload." + element + ".value.length")
,则只需将characters
与words
分开,此语句250 words
将返回value of textarea
而非space
的否并使用max words allowed
进行验证,然后返回相应的消息:
您可以尝试使用此代码。
function maxlength(element, maxvalue) {
var q = eval("document.upload." + element + ".value");
var textLength = q.split(/\S+/).length - 1
var r = textLength - maxvalue;
var msg = "Sorry, you have input " + textLength + " characters into the " +
"text area box you just completed. It can return no more than " + maxvalue + " words to be processed. Please abbreviate " +
"your text by at least " + r + " words";
if (textLength > maxvalue) alert(msg);
}