输入值以部分匹配数组中的项并返回true

时间:2018-01-29 17:27:45

标签: jquery arrays forms

我目前正在制作一个表单,用户可以通过输入邮政编码来检查我们是否向他们的区域发送邮件。如果输入值部分匹配“E1”,我有一个工作代码但如果值部分匹配“E1,E2,E3一直到E18。”我需要这个。

EG。如果用户输入E2 4EJ,则返回true。

我目前正在使用的代码如下。任何有关我需要改变的建议都将不胜感激!

HTML

#include <iostream>
#include <sstream>

//Returns integer from user input
int user_input(void);

//Returns the 'nth' fibonacci number
int fib(int);

int main () {
    int n = user_input();
    char fib_arr[n];
    std::fill_n(fib_arr, n, 'f');
    int ith_fib = 0;
    //loop until either the 'ith' fib number exceeds our array size or i exceeds
    //array size.
    for (int i = 0; i < n && ith_fib < n; i++)
    {
        ith_fib = fib(i);
        fib_arr[ith_fib] = 'F';
    }
    fib_arr[n] = '\0';
    std::cout << fib_arr << std::endl;
    return 0;
} 

//Returns integer from user input
int user_input() 
{
    int int_input = 0;
    std::string str_input = "";
    bool is_valid_int = false;
    while(!is_valid_int) 
    {
        std::cout << "Enter a positive number." << std::endl;
        //copy user input into str_input
        getline(std::cin, str_input);
        //convert str_inpt into a string stream object
        std::stringstream input_stream(str_input);
        //test to see if input_stream is of integer type and even and greater than 2.
        if(input_stream >> int_input)
        {
            is_valid_int = true;
        }

    }
    std::cout << "you entered " << int_input << std::endl;

    return int_input;
}
//Returns the 'nth' fibonacci number
int fib(int n)
{

    if(n == 0)
    {
        return 0;
    }
    else if(n ==1)
    {
        return 1;
    } 
    else
    {
        return (fib(n-1) + fib(n-2));   
    }
}

的jQuery

<form id="searchForm">
    <input type="text" placeholder="First half of your postcode...">
    <button type="submit" value="Search">Submit</button> 
</form>

<div id="result"></div>

代码我正在玩

$('#searchForm').submit(function(){
    var postcode = $('#searchForm input').val();  
    if (postcode.indexOf('E1') == 0) {
        $('#result').html('Yes, we deliver!');
    } else {
        $('#result').html('Sorry, we don't deliver!');
    }
    return false;
});

修改

在下面给出正确的答案之后,我的最终代码是:

 var postcodes = ["E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "E10", "E11", "E12", "E13", "E14", "E15", "E16", "E17", "E18"];

1 个答案:

答案 0 :(得分:1)

您可以迭代每个邮政编码并查找匹配项。如果匹配显示正消息,否则显示否定消息:

var postcodeAreaDeliverable = false;
$.each( obj, function( key, value ) {
  if (obj.match("^" + value) {
    postcodeAreaDeliverable = true;
  }
});
if (postcodeAreaDeliverable) {
  $('#result').html('Yes, we deliver!');
} else {
  $('#result').html('Sorry, we don't deliver!');
}