MisterWeary
MisterWeary

Reputation: 605

Using jQuery to match a select option

I've created some JavaScript to check if a username is already listed in the options of a "SELECT" box on my form. It works perfectly but I am fairly sure there must be a neater way of doing it by utilising jQuery better. I've tried searching through the jQuery API, Google and StackOverflow and don't seem to be having any luck finding guidance. If anyone can give me some pointers it would be much appreciated.

Here is the working code I'm currently using:

// CHECK IF THE USERNAME ALREADY EXISTS
var found     = false;
var users     = document.admin_form.user_list.options;
var num_users = users.length;
if (num_users != 0) {
   var name_in_list;
   var i           = 0;
   var name_chosen = $("[name=user_name]").val().toLowerCase();
   while ((i < num_users) && !found) {
      name_in_list = users[i].text.toLowerCase();
      if (name_chosen == name_in_list) {
         found = true;
      }
      i++;
   }
}
if (found) {
   $("#user_err").text("That USERNAME already exists, try again");
   $("[name=user_name]").val("");
   $("[name=user_name]").focus();
}

Thanks in advance!

Upvotes: 0

Views: 3181

Answers (3)

Terry
Terry

Reputation: 14219

Misread earlier, here is updated code:

if($('#user_list option[value="' + name_chosen + '"]').length) return true;

Upvotes: 0

Blender
Blender

Reputation: 298106

You could try this:

var users = $('#user_list option').map(function() { return this.value; }).get();

if ($.inArray($("[name=user_name]").val().toLowerCase(), users)) {
   $("#user_err").text("That USERNAME already exists, try again");
   $("[name=user_name]").val('').focus();
}

As @John pointed out, you could try a selector (upvote him, not me):

if ($('#user_list option[value="' + $("[name=user_name]").val().toLowerCase() + '"]').length > 0){
   $("#user_err").text("That USERNAME already exists, try again");
   $("[name=user_name]").val('').focus();
}

Upvotes: 1

John
John

Reputation: 975

You can traverse the nodes of a select just like any other element.

if($('select option[value="some value"]').length>0) return true;

Upvotes: 4

Related Questions