简体   繁体   English

输入中第11个逗号后发出警报

[英]Alert after 11th comma in an input

I want to alert when user enter comma (,) 11th time. 我想在用户第11次输入逗号(,)时发出警报。 How can I do this with jQuery or js? 我该如何使用jQuery或js?

<input class='myprofiletags' name='my_profile_tags' value='<?php echo $my_profile_tags; ?>' placeholder="" />

What I am doing: 我在做什么:

jQuery('.myprofiletags').keyup(function()
{
  if( jQuery(this).val().indexOf(',') !== -1 )
  {
      alert('No more text allowed');
  }
}

This script above always alerts, even when I press and character after one comma. 上面的脚本始终会发出警报,即使我在一个逗号后按和字符也是如此。

Any help would be appreciated. 任何帮助,将不胜感激。

按逗号分割,如果有10个以上,则发出警报:

jQuery(this).val().split(',').length > 10

A simple regular expression will handle this... 一个简单的正则表达式可以解决这个问题。

jQuery('.myprofiletags').keypress(function(e)
{
    if (jQuery(this).val().match(/,/g).length > 10)
    {
        e.preventDefault();  // stops the keypress occuring
        alert('No more text allowed');
    }
});

I also changed it to use keypress stopped further entry as your example code would alert the user, but not actually stop them entering further text. 我还更改了它以使用keypress停止进一步输入,因为您的示例代码将警告用户,但实际上并未阻止他们输入进一步的文本。

jsfiddle example... jsfiddle示例...

http://jsfiddle.net/3sah4xsm/ http://jsfiddle.net/3sah4xsm/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM