选中选择框值并将其与输入进行比较

时间:2012-12-25 06:57:48

标签: javascript jquery

我想检查textfield,newTeamName是否已经存储在选择框中的团队名列表中。不幸的是,我的代码不起作用 - 它有什么问题?哦,我没有控制台问题。

    optionList = [];
    $('#chooseTeam option').each(function() {
        optionList.push($(this).val())
    });
    if (form.newTeamName.value in optionList) {
        $("#text-error").html("Team exists");
        $('#text-error').fadeIn(400).delay(3200).fadeOut(800);
        return false;
    }

小更新:

哦,我的form.name.value工作正常,因为它们适用于其他if语句。

3 个答案:

答案 0 :(得分:1)

optionList是用于对象属性(或数值数组索引)的数组in,您可以使用indexOf来测试值是否在数组中

optionList = [];
$('#chooseTeam option').each(function() {
    optionList.push($(this).val())
});
if (optionList.indexOf(form.newTeamName.value) > -1) {
    $("#text-error").html("Team exists");
    $('#text-error').fadeIn(400).delay(3200).fadeOut(800);
    return false;
}

答案 1 :(得分:0)

修正了它。

    $('#chooseTeam option').each(function() {
        if (form.newTeamName.value == $(this).val()){
            $("#text-error").html("Team exists");
            $('#text-error').fadeIn(400).delay(3200).fadeOut(800);
            return false;
        }
    });

答案 2 :(得分:0)

尝试这样的事情

  my_array = Array();

  //To find if a value or element exists in an array
  if (my_array.indexOf(‘find_this_value’) != -1)
  {
        alert(‘Value exists in array.’);
  }

 //To find if a value or element DOES NOT exist in an array
 if (my_array.indexOf(‘find_this_value’) == -1)
 {
     alert(‘Value does not exist in array.’);
 }
相关问题