Question

I'm trying to create a page for a friend with allergies, where users can input a food item and get a response as to whether or not my friend is allergic to it. I've created an array with all his food allergies and the intent is that when the user enters any given food and hits submit, the page will respond with an alert.

I'm new to jquery and have hacked together a couple of close examples, but clearly I'm missing some connecting piece. Any help would be appreciated!

Working demo: http://jsfiddle.net/ssprockett/Ct2TU/1/

Here is the jquery so far:

$('.submit').click(function () {
   if( $.inArray( $("input:text").val().toUpperCase(), ["cantaloupe", "almonds", "almond flour", "almond flour", "almond milk", "hazel nuts", "hazelnuts", "filberts", "pecans", "peanuts", "english walnuts", "watermelons", "grapefruit", "orange", "garlic", "mustard", "green pepper", "navy bean", "string bean", "cabbage", "carrot", "cauliflower", "lettuce", "bass", "peas", "sweet potatoes", "squash", "clams", "barley", "oat", "soy", "wheat", "rice", "gluten", "sea bass", "mustard seeds",  ] ) > -1 )  {
        alert("Nope. This will make him sick.");

    } else {

        alert("Yep. This is fine.");
    }
Was it helpful?

Solution

There are a few minor issues:

  1. You're not including jQuery in the jsfiddle
  2. You were missing a closing }) for the click binding function
  3. You should be using .toLowerCase, not .toUpperCase since all of the values of your array are lower-cased.

http://jsfiddle.net/Ct2TU/4/

OTHER TIPS

toUpperCase() makes all of those values false. Try toLowerCase()

Here is one working example:

http://jsfiddle.net/jA7MB/

var allergy = ["cantaloupe", "almonds", "almond flour", "almond flour", "almond milk", "hazel nuts", "hazelnuts", "filberts", "pecans", "peanuts", "english walnuts", "watermelons", "grapefruit", "orange", "garlic", "mustard", "green pepper", "navy bean", "string bean", "cabbage", "carrot", "cauliflower", "lettuce", "bass", "peas", "sweet potatoes", "squash", "clams", "barley", "oat", "soy", "wheat", "rice", "gluten", "sea bass", "mustard seeds"];

$( ".submit" ).click(function() {
  if(($.inArray($('#food').val().toLowerCase(), allergy)) != -1){
   alert( "allergic!")
  } else alert("not allergic!");

});

You can try it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top