Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make div appear depending on multiple text inputs using jQuery

Tags:

jquery

regex

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

like image 432
Italian David Avatar asked Feb 16 '23 17:02

Italian David


2 Answers

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);
});

Here's a fiddle

like image 178
billyonecan Avatar answered Feb 18 '23 09:02

billyonecan


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.

like image 29
Code Lღver Avatar answered Feb 18 '23 11:02

Code Lღver