使用jQuery根据多个文本输入显示div

时间:2013-08-01 08:38:26

标签: jquery regex

我正在尝试根据输入到输入中的值(邮政编码)是否包含一组预定义的字符来淡入淡入淡出。我已经设法让它为一个值工作,但我希望它能够处理多个输入,因为最终会有多个邮政编码。如果我可以让它忽略空格和大小写也是好的,所以我可以为每个邮政编码放一个值而不是像我在这里做的那样五个:

$(".postcode-checker").click(function()
{
 var name = $("#postcode-form input").val();
 if(name != '')
{
   if ($("#postcode-form input").val().indexOf("BS2 9","bs2 9","BS29","bs29","Bs2 9","Bs29") > -1)
   {
    $('#bpwdp').fadeIn(500);
   }
 }
});

http://jsfiddle.net/x8NwW/

如果您输入'BS2 9',它可以工作,但不会出现以下任何值,例如: 'bs2 9'没有。

我一直在阅读,我不确定正则表达式,.indexOf或.match是否是答案,但我不确定如何在此上下文中实现它们。

非常感谢任何帮助

2 个答案:

答案 0 :(得分:5)

删除空格,转换为大写,然后您只需将字符串的开头与BS29进行比较:

$(".postcode-checker").click(function() {
   var name = $("#postcode-form input").val().replace(/\s+/g, '').toUpperCase();    
   $('#bpwdp')[name.match(/^BS29/) ? 'fadeIn' : 'fadeOut'](500);
});

Here's a fiddle

答案 1 :(得分:3)

由于indexof正确,您的if条件不正确,因此请使用以下代码:

var postcode = ["BS2 9","bs2 9","BS29","bs29","Bs2 9","Bs29"];
if (postcode.indexOf($("#postcode-form input").val()) > -1){...}

indexOf的正确语法是:

array1.indexOf(searchElement[, fromIndex]);
^^^              ^^^ data that you will search
data from which you search

教程是here

相关问题