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

C_Ogoo
  • 5,365
  • 3
  • 17
  • 34
Simon Staton
  • 3,947
  • 2
  • 22
  • 47
  • 2
    Check if `value.indexOf("BT")` **is** `0`, not just `>= 0` – Ian Jul 25 '13 at 15:19
  • possible duplicate of [JavaScript - check if string starts with](http://stackoverflow.com/questions/15310917/javascript-check-if-string-starts-with) – Felix Kling Jul 25 '13 at 15:22
  • possible duplicate of [Javascript StartsWith](http://stackoverflow.com/questions/646628/javascript-startswith) – Ian Jul 25 '13 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 Jul 25 '13 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 Jan 23 '14 at 09:54

2 Answers2

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");
    }
})
Adil
  • 139,325
  • 23
  • 196
  • 197
0

a regex solution:

$('.cart-postcode2').keyup(function(){
    var value = $(this).val();
    if (value.match(/^BT/)) {
      alert("is ireland");
    }
})
jmarkmurphy
  • 9,829
  • 28
  • 51
Plato
  • 9,788
  • 2
  • 36
  • 58
  • 1
    The regex solution was wrong - it didn't have the `^` to make sure it **started with** "BT" – Ian Jul 25 '13 at 15:24
  • yup, i edited it, but then it got deleted... can't hurt to have multiple options available for future ppl finding the thread tho :) – Plato Jul 25 '13 at 15:25