Reputation: 1445
I would like to check if a textfield, newTeamName is already in a list of teamnames stored in a select box. Unfortunately, my code does not work - what's wrong with it? Oh and I have no console problems.
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;
}
Small Update:
Oh and my form.name.value's work fine as they work for other if statements.
Upvotes: 1
Views: 294
Reputation: 10906
try something like this
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.’);
}
Upvotes: 0
Reputation: 1445
Fixed it.
$('#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;
}
});
Upvotes: 0
Reputation: 97727
optionList
is an array in
used for object properties(or numeric array indices), you can use indexOf
to test if a value is in an array
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;
}
Upvotes: 1