简体   繁体   English

尝试使用jquery创建带有多个错误答案的文本输入

[英]Trying to use jquery to create text input with multiple wrong answers

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. 我是jquery的新手,并整理了一些紧密的示例,但显然我缺少一些相关的内容。 Any help would be appreciated! 任何帮助,将不胜感激!

Working demo: http://jsfiddle.net/ssprockett/Ct2TU/1/ 工作演示: http : //jsfiddle.net/ssprockett/Ct2TU/1/

Here is the jquery so far: 到目前为止,这是jquery:

$('.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.");
    }

There are a few minor issues: 有一些小问题:

  1. You're not including jQuery in the jsfiddle 您没有在jsfiddle中包括jQuery
  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. 您应该使用.toLowerCase ,而不是.toUpperCase因为数组的所有值都是小写的。

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

toUpperCase() makes all of those values false. toUpperCase()使所有这些值都为false。 Try toLowerCase() 尝试toLowerCase()

Here is one working example: 这是一个工作示例:

http://jsfiddle.net/jA7MB/ 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. 你可以试试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM