检测何时将文本输入到文本区域并相应地进行更改

我有一个textarea ,用户可以在其中输入或粘贴其他人的电子邮件地址,并在按下“提交”按钮后向他们发送邀请。 在提交表单之前,每封电子邮件必须用逗号分隔并且有效 – validation由jQuery Validate插件和multiemail方法处理 。

问题

有些人直接从他们的电子邮件客户端粘贴电子邮件地址,这些电子邮件通常是一种奇怪的格式 – 在实际电子邮件之前包含姓名和姓氏,或者电子邮件包含在中。 例如: "The Dude" , "The Dudette"

我想要做的是使用jquery从批量文本中提取所有电子邮件地址 ,但是我在将这段代码与我的textarea一起工作时遇到了问题 – 我不知道从哪里开始。

我如何使用上面答案中的代码提取输入逗号后输入到textarea每封电子邮件,或者当焦点从textarea移开时? 因此,如果我粘贴"The Dude" 并键入,之后或切换焦点,输入的值将更改为the.dude@gmail.com

我猜是这样的:

 var textarea = $('#emails'); textarea.on({ keyup: function(e) { if (e.which === 188) check(); }, blur: check }); function check() { var val = $.trim(textarea.val()), err = ''; if (!val.length) { err = 'No input ?'; return; } var emails = val.split(','), notvalid = [], temp = []; $.each(emails, function(_,mail) { mail = $.trim(mail); if ( mail.length ) { var m = mail.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi); if (m) { temp.push(m); }else{ temp.push(mail); notvalid.push(mail) } }else{ temp.push(mail); } if (notvalid.length) err = 'Not valid emails : ' + notvalid.join(', '); }); $('#error').html(err); textarea.val((temp.length ? temp : emails).join(', ')); } 

小提琴

您可以使用事件处理程序检测textarea何时更改(或其他输入字段)。 Jquery支持多个事件(请查看http://api.jquery.com/category/events/ )。 在这种特殊情况下,我应该使用keyup事件来触发extractEmails函数。 这样你的提取将是“活的”。 但是,通过捕捉模糊或改变事件也是可能的。

使用keyup eventhandler

http://jsfiddle.net/kasperfish/9hLtW/5/

 $('#text').on('keyup',function(event) { emails=extractEmails($(this).val()); $("#emails").text(emails); }); function extractEmails (text) { return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi); } 

当您失去焦点或输入逗号时,这会将输入的文本转换为电子邮件:

 function extractEmails (text) { return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi); } $("#emailtext").on('keypress blur', function(e) { if (e.which === 44 || e.type =="blur") { $('#emails').text(extractEmails($("#emailtext").val())); } }); 

这是小提琴:

http://jsfiddle.net/Mj2KM/