如何将元素存储到数组中,并检查是否存在值?

时间:2011-08-10 15:26:05

标签: php jquery arrays forms validation

我正在创建一个表单,允许您在我们的网站上注册警报,允许用户将关键字输入到表单中。

我已经设置了验证,虽然我使用的jquery对我来说似乎有点费解,但它确实有效!

我现在正在尝试设置表单,以便在您输入关键字时,它会检查您是否已经放入该关键字。

e.g。我已将“云”添加到我的列表中,并且我不小心尝试再次添加它,表单应该提醒我并且不允许我将其添加到我的列表中。

我认为解决方案是将关键字存储在“KeywordList”数组中,然后像PHP一样循环使用for循环:

foreach (KeywordList as KeywordListArrayElement){
         if(KwValue == KeywordListArrayElement){
           alert ("The keyword '+KwValue+' has already been added");
           return false;
         }
}

但我不知道如何在数组中存储关键字或从中获取

这是我的HTML:

    <form action="" method="get" name="Test Form" target="_self" id="alerts_form" dir="ltr" lang="en">
        <fieldset id="alerts_options">
            <label for="email_address">Email: </label>
            <input type="text" id="email_address" name="email_address" tabindex="1" autofocus="autofocus" autocomplete="on" required="required" value="" /><div class="email-alert form_val" style="display: none;">Please enter a valid email address</div><br />
            <label for="keywords">Keyword(s): </label>
            <input type="text" id="keywords" name="keywords[]" tabindex="2" autocomplete="on" value="" />
            <button id="addKeyword" name="addKeyword" value="">+</button><br />
            <div id="KeywordList"></div>
            <div class="keyword-alert form_val" style="display: none;">Please input at least one keyword</div>
            <label for="frequency">Frequency: </label>
            <select tabindex="3" id="frequency" name="frequency"><br />
            <optgroup>
            <option selected="selected" value=""></option>
            <option value="1">Daily</option>
            <option value="7">Weekly</option>
            <option value="30">Monthly</option>
            </optgroup>
            </select><div class="frequency-alert form_val" style="display: none;">Please make a selection</div><br />
            <input type="hidden" id="Step" name="Step" value="2" />
            <div class="clear"></div>
            <button class="alert_button" type="submit" id="submit" name="UpdateAlertOption" value="Unconfirmed">Submit</button><br />
            <button class="alert_button" type="submit" name="UpdateAlertOption" value="Delete">Delete</button><br />
            <button class="alert_button" type="submit" name="UpdateAlertOption" value="Delete All">DeleteAll</button>
            <input type="hidden" value="" name="" class="KwdBox" />
        </fieldset>
    </form>

这是我的JQuery:

<script type='text/javascript'>
jQuery(document).ready(function($){

    $("#addKeyword").click(function(event) {
    event.preventDefault();
    var KwValue = $("#keywords").val();
    if($("#keywords").val()==""){
        alert('Please input a keyword');
        }

        else
        {
            var squareBrackets = "[]";

                $("#keywords").css('background-color', '#FFFFFF');
                $("#alerts_options .keyword-alert").hide();
            $('<input type="text" class="KwdBox" name="keywords'+squareBrackets+'" value="'+KwValue+'" tabindex="2" autocomplete="on" required="required"/>')
            .appendTo('#KeywordList');
            $("#keywords").val("");
            $(".KwdBox").click(function(event){
                event.preventDefault();
                $(this).remove();

            });
        }
    });

    $("#alerts_options .email-alert").hide();
    $("#alerts_options .keyword-alert").hide();
    $("#alerts_options .frequency-alert").hide();

    $("#submit").click(function(){


        var frequency = 1;
        if($("[name=frequency]").val()==""){
        frequency = 0;
        }else{
        frequency = 1;
        }
        var keyword = 1;
        if($("#keywords").val()=="") {
        keyword = 0;
        }
        if($(".KwdBox").val() >""){
        keyword = 1;
        }
        var email = 1;
        if(!checkEmail($("[name=email_address]").val())){
        email = 0;
        }else{
        email = 1;
        }
        //frequency empty, email empty, kw empty
        if(frequency == 0 && email == 0 && keyword == 0){
            $("#keywords").css('background-color', 'rgb(255, 232, 232)');
            $("[name=email_address]").css('background-color', 'rgb(255, 232, 232)');
            $("[name=frequency]").css('background-color', 'rgb(255, 232, 232)');        
            $("#alerts_options .form_val").show();
            return false;
        }
        else{
            $("#alerts_options .form_val").hide();
        } //frequency empty, email on, kw empty
        if(frequency == 0 && email > 0 && keyword == 0){
            $("#keywords").css('background-color', 'rgb(255, 232, 232)');
            $("[name=email_address]").css('background-color', '#FFFFFF');
            $("[name=frequency]").css('background-color', 'rgb(255, 232, 232)');    
            $("#alerts_options .email-alert").hide();
            $("#alerts_options .keyword-alert").show();
            $("#alerts_options .frequency-alert").show();
            return false;
        }//frequency empty, email on, kw on
        if(frequency == 0 && email > 0 && keyword > 0){
            $("#keywords").css('background-color', '#FFFFFF');
            $("[name=email_address]").css('background-color', '#FFFFFF');
            $("[name=frequency]").css('background-color', 'rgb(255, 232, 232)');
            $("#alerts_options .email-alert").hide();
            $("#alerts_options .keyword-alert").hide();
            $("#alerts_options .frequency-alert").show();
            return false;
        }//frequency on, email on, kw empty
        if(frequency > 0 && email > 0 && keyword == 0){
            $("#keywords").css('background-color', 'rgb(255, 232, 232)');
            $("[name=email_address]").css('background-color', '#FFFFFF');
            $("[name=frequency]").css('background-color', '#FFFFFF');
            $("#alerts_options .email-alert").hide();
            $("#alerts_options .keyword-alert").show();
            $("#alerts_options .frequency-alert").hide();
            return false;
        }
        if(frequency > 0 && email == 0 && keyword > 0){
            $("#keywords").css('background-color', '#FFFFFF');
            $("[name=email_address]").css('background-color', 'rgb(255, 232, 232)');
            $("[name=frequency]").css('background-color', '#FFFFFF');
            $("#alerts_options .email-alert").show();
            $("#alerts_options .keyword-alert").hide();
            $("#alerts_options .frequency-alert").hide();
            return false;
        }
        if(frequency == 0 && email == 0 && keyword > 0){
            $("#keywords").css('background-color', '#FFFFFF');
            $("[name=email_address]").css('background-color', 'rgb(255, 232, 232)');
            $("[name=frequency]").css('background-color', 'rgb(255, 232, 232)');
            $("#alerts_options .email-alert").show();
            $("#alerts_options .keyword-alert").hide();
            $("#alerts_options .frequency-alert").show();
            return false;
        }
            if(frequency > 0 && email == 0 && keyword == 0){
            $("#keywords").css('background-color', 'rgb(255, 232, 232)');
            $("[name=email_address]").css('background-color', 'rgb(255, 232, 232)');
            $("[name=frequency]").css('background-color', '#FFFFFF');
            $("#alerts_options .email-alert").show();
            $("#alerts_options .keyword-alert").show();
            $("#alerts_options .frequency-alert").hide();
            return false;
        }

    });
});
</script>

2 个答案:

答案 0 :(得分:3)

您不必使用数组。请改用map / associative-array。你可以这样做:

var keywords = {};

然后,如果您的关键字位于变量keyword中,则可以执行以下操作:

keywords[keyword] = true;

因此,如果你有关键字cloud,你基本上拥有的是:

keywords['cloud'] = true;

要检查它的存在,您所要做的就是:

if(keywords[keyword]) {
  ...
}

现在要将您的关键字添加到列表中,您可以执行以下操作:

var KwValue = $("#keywords").val();

var keywordArray = KwValue.split(/\s*,\s*/); //assuming that your keywords are separated by commas:

for(var i = 0; i < keywordArray.length; i++) {
    var keyword = keywordArray[i];

    if(!keywords[keyword]) {
       keywords[keyword] = true;
       ...
    }
}

这是O(n),但它比数组中的O(n 2 )更好。

答案 1 :(得分:1)

最简单的方法,最便宜的是使用数组(你是),但是将关键字作为数组的键放入数组中:

var keywords = {}; // not really an array, but we'll just pretend it is

keywords['hello'] = true;
keywords['there'] = true;
etc...

之后,检查关键字的存在是一件简单的事情

if (keywords[yourvarhere]) {
  ... it exists
}

每次需要检查特定关键字时,可以节省搜索数组的全部开销。