最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery if input starts with a value - Stack Overflow

programmeradmin5浏览0评论

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

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?

So typing BT2 9NH will alert "Ireland" but typing OX2 8BT will not

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

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?

So typing BT2 9NH will alert "Ireland" but typing OX2 8BT will not

Share Improve this question edited Jan 6, 2020 at 11:10 C.OG 6,5293 gold badges23 silver badges41 bronze badges asked Jul 25, 2013 at 15:18 Simon StatonSimon Staton 4,5054 gold badges31 silver badges50 bronze badges 5
  • 2 Check if value.indexOf("BT") is 0, not just >= 0 – Ian Commented Jul 25, 2013 at 15:19
  • possible duplicate of JavaScript - check if string starts with – Felix Kling Commented Jul 25, 2013 at 15:22
  • possible duplicate of Javascript StartsWith – Ian Commented Jul 25, 2013 at 15:22
  • Do you want the alert to on each key typed after BT is found or only once when it's first encountered? – Kevin Le - Khnle Commented Jul 25, 2013 at 15:23
  • The proper way for us is to rollback such edits. Proper way for you is to delete the question (which is quite unfair to @Adil). Please do not edit questions this way. Thanks! – TLama Commented Jan 23, 2014 at 9:54
Add a ment  | 

2 Answers 2

Reset to default 15

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

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

a regex solution:

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

评论列表(0)

  1. 暂无评论