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!
You can traverse the nodes of a select just like any other element.