Javascript 限制输入框中的字
我有一个名为“title”的输入框 我希望用户只输入35个单词,不超过这个数字Javascript 限制输入框中的字,javascript,jquery,html,ajax,Javascript,Jquery,Html,Ajax,我有一个名为“title”的输入框 我希望用户只输入35个单词,不超过这个数字 <input name="title" id="title" class="event-name gui-input" placeholder="Title" type="text"> <script type="text/javascript"> /* <![CDATA[ */ jQuery(function(){ jQuery("#title").v
<input name="title" id="title" class="event-name gui-input" placeholder="Title" type="text">
<script type="text/javascript">
/* <![CDATA[ */
jQuery(function(){
jQuery("#title").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter Title"
});
});
</script>
/*
使用JavaScriptsplit
方法:
var content = $("input#title").val() //content is now the value of the text box
var words = content.trim().split(/\s+/); //words is an array of words, split by space
var num_words = words.length; //num_words is the number of words in the array
if(num_words>35){
//too many words
return false;
}
希望这会有所帮助,并且您可以根据验证调整此代码
一行解决方案返回输入中的字数:
var num_words = $("input#title").val().trim().split(/\s+/).length;
只需在输入字段中使用最大长度即可
<input name="title" id="title" class="event-name gui-input"
placeholder="Title" type="text" maxlength="35">
我修改了Ben提供的解决方案。 让用户知道剩下多少单词 脚本
$("#title").keyup(function(){
var content = $("#title").val(); //content is now the value of the text box
var words = content.split(/\s+/); //words is an array of words, split by space
var num_words = words.length; //num_words is the number of words in the array
var max_limit=35;
if(num_words>max_limit){
alert("Exceeding the max limit");
var lastIndex = content.lastIndexOf(" ");
$("#title").val(content.substring(0, lastIndex));
$('#remainingChars').text('Limit Exceeding');
return false;
}
else
{
$('#remainingChars').text(max_limit+1-num_words +" words remaining");
}
});
表单字段
<input name="title" type="text" id="title" size="100" />
<div id="remainingChars">Max limit is 35 words.</div>
最大限制为35个字。
您可以在
keyup
事件上编写以下逻辑
35个单词=34个空格
maxlength
attribute?@Tushar maxlength用于字符吗?不是单词吗?我需要一个脚本,在用户键入剩余的20个单词时告诉他,依此类推,到目前为止您尝试了什么?这不是免费的编程服务,您需要,我们编码。如果您不确定从哪里开始,为什么不使用.split()
并计算返回的数组。“从每个空间分割”我没有要求提供免费代码@NewToJS,我已经给出了上面的jquery脚本,我想知道如何阻止用户写更多的单词。。。ok dude?maxlength
用于字符-OP正在查找字数。请在if
语句中输入所需内容以获得响应。根据你的喜好编辑它。例如,if(num_words>35){alert(“太长”);}else{alert(“长度很好”)}
我会使用\s+
来拆分单词删除字符串末尾的空格,否则它将返回一个空数组,但仍将其计为一个单词。@NewToJS在使用\s+
拆分单词hanks@Tushar时不是必需的,您是正确的-添加了regex和JSFiddle示例。您的意思是您对现有答案做了一些更改,试图为它做标记。。。对答案的修改应该在评论中提出,而不是转载。这就是我提到的原因。提供更好的解决方案。不适用于标记如果用户在末尾加空格,这也会有计算单词的相同问题<代码>示例这是一个很好的观点。谢谢:)现在你可以拿马克兄弟了;)干杯我没有提交答案,因为我会提供相同的答案,但改动很少,因此提出了一个建议,以使答案更好。你不会在评论中被标记,兄弟:)