jQuery find selection values on multiple dropdowns

Hi,

I’ve got a form which I want to validate using jQuery to ensure that the same value for a dropdown has not been entered more than once.

The form consists of the following:


<li class="clonedInput" id="input1">
Name:
<select id="player[1][userid]" name="player[1][userid]"></select>
<select class="hours" id="player[1][hours]" name="player[1][hours]"></select>
<select class="mins" id="player[1][mins]" name="player[1][mins]"></select>
</li>

<li class="clonedInput" id="input2">
Name:
<select id="player[2][userid]" name="player[2][userid]"></select>
<select class="hours" id="player[2][hours]" name="player[2][hours]"></select>
<select class="mins" id="player[2][mins]" name="player[2][mins]"></select>
<li>

<li class="clonedInput" id="input3">
Name:
<select id="player[3][userid]" name="player[3][userid]"></select>
<select class="hours" id="player[3][hours]" name="player[3][hours]"></select>
<select class="mins" id="player[3][mins]" name="player[3][mins]"></select>
<li>

As you can see, each player has a userid, hours and mins dropdown

I want to make sure that the userid is not duplicated on submit.

I’m not sure how I find each userid per player and then hold it to compare to other userids submitted

I do not have to use jQuery but from my investigations so far it would seem to offer the best solution but I’m open to all ideas!

Any guidance on this is greatly appreciated.

thanks

aor

This is how it is normally done:

[list][]retrieve the values from the user id fields
[
]extract their values in to an array
[]check for duplicates among those values
[
]show an error message of some kind
[*]prevent the form submission
[/list]

You can use the Attribute Ends With Selector to retrieve the values

The each is a useful way to process those values, and add their values to a new array

Checking for duplicates is just a matter of looping backwards through the array, and using Array.indexOf() to check if the value exists at some earlier part of the array.

In regards to the error message, if you’re using jQuery validation then you can use [url=“http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage”]addMethod for the checking code, so that an error message is automatically placed where needed.

apologies for not replying sooner pmw57…
your instructions worked perfectly thanks…
the javascript code i am now using is


var cCheck = new Array ();
	
	$('select[name$="[userid]"]').each(function(i) {
		if (cCheck.indexOf($(this).val()) == -1) {
			cCheck.push($(this).val());
		}
		else {
			alert("You have already entered a name more than once");
			return false;
		}
	});

this may or may not be of use to others!

thanks again

aor