I'm trying to make a div fade in depending on the whether value (postcode) entered into an input includes a predefined set of characters. I have managed to get it to work for one value but I would like it to work on multiple inputs as eventually there will be multiple postcodes. It would also be good if I could make it ignore spaces and cases so I could just put one value for each postcode and not five as I have done here:
$(".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/
If you enter 'BS2 9' it works but none of the following values e.g. 'bs2 9' don't.
I've been reading around and I'm not sure if a regular expression, .indexOf, or .match would be the answer but I'm not really sure how to implement them in this context.
Any help would be greatly appreciated
Remove the whitespace, convert to uppercase and then you can just compare the start of the string with BS29
:
$(".postcode-checker").click(function() {
var name = $("#postcode-form input").val().replace(/\s+/g, '').toUpperCase();
$('#bpwdp')[name.match(/^BS29/) ? 'fadeIn' : 'fadeOut'](500);
});
Your if condition is not correct as indexof
is correct so use the below code:
var postcode = ["BS2 9","bs2 9","BS29","bs29","Bs2 9","Bs29"];
if (postcode.indexOf($("#postcode-form input").val()) > -1){...}
The right syntax of indexOf is be :
array1.indexOf(searchElement[, fromIndex]);
^^^ ^^^ data that you will search
data from which you search
Tutorial is here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With