javascript JQuery 如果输入以值开头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17862085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:53:31  来源:igfitidea点击:

JQuery if input starts with a value

javascriptjquery

提问by Simon Staton

I am managing to check the value inside a postcode input field using the following:

我设法使用以下方法检查邮政编码输入字段中的值:

html:

html:

<input type="text" class="cart-postcode2" size="10" tabindex="22">

JQuery:

查询:

$('.cart-postcode2').keyup(function(){
    var value = $(this).val();
    if (value.indexOf('BT') >= 0) {
        alert("is ireland");
    }
})

This is working great however I want it to only alert if it starts with BT and does not contain BT in any part of the value, does anyone know if this is possible?

这很好用,但是我希望它只在它以 BT 开头并且值的任何部分都不包含 BT 时发出警报,有人知道这是否可能吗?

So typing BT2 9NHwill alert "Ireland" but typing OX2 8BTwill not

所以打字BT2 9NH会提醒“爱尔兰”但打字OX2 8BT不会

回答by Adil

You can check if string starts with BT, as indexOf()will give index zero if value stats with BT

您可以检查字符串是否以 开头BTindexOf()如果使用 BT 的 value stats 将给出索引零

$('.cart-postcode2').keyup(function(){
    var value = $(this).val();
    if (value.indexOf('BT') == 0) {
      alert("is ireland");
    }
})

回答by Plato

a regex solution:

正则表达式解决方案:

$('.cart-postcode2').keyup(function(){
    var value = $(this).val();
    if (value.match(/^BT/)) {
      alert("is ireland");
    }
})