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
-
2
Check if
value.indexOf("BT")
is0
, 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
2 Answers
Reset to default 15You 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");
}
})