Reputation: 1306
Hopefully this should be quite a quick one!
I have a list of <select>
elements on my page. Each of these drop-downs is a list of booking times for an online parents evening booking system.
Each select looks like this:
<select class="appointments" id="14" name="appointments[]">
<option>.. Select:</option>
<option value="1">[ 4:00 ]</option>
<option value="2">[ 4:05 ]</option>
<option value="3">[ 4:10 ] Eliza Fox</option>
<option value="4">[ 4:15 ]</option>
<option value="5">[ 4:20 ]</option>
<option value="6">[ 4:25 ] diane davison</option>
<option value="7">[ 4:30 ]</option>
<option value="8">[ 4:35 ]</option>
<option value="9">[ 4:40 ]</option>
<option value="10">[ 4:45 ]</option>
</select>
Depending on who has booked and who hasn't. The value
integers are the booking slot specific to that time.
I don't want parents to be able to book two appointments at the same time, so I was thinking I could use jQuery to get an array of the value
of each <select>
element, then see if there are any duplicates.
If duplicates are found, I'd like to stop the form from being submitted and display an alert
.
Thanks in advance,
Upvotes: 0
Views: 803
Reputation:
Use this function
if it returns false then there's a duplicate ..
function validateTimes(){
var appointmentsArray=[];
$(".appointments").each(function(){
if( $.inArray( $(this).val() , appointmentsArray ) > -1 ){
return false;
}
} );
return true;
}
Upvotes: 2
Reputation: 94101
Maybe this is a bit more complicated but what it does is it checks for time duplicates instead of value
duplicates. Don't know how useful this will be but here you go:
var isDup = function() {
var $options = $('select').find('option'),
opts = [],
dup = false;
$options.each(function() {
// Regex could be better, matches 99:99 for example...
var value = $(this).text().match(/\d+:\d+/);
if (!~$.inArray(String(value), opts)) {
opts.push(String(value));
} else {
dup = true;
return false;
}
});
return dup;
};
You can use it like this http://jsfiddle.net/elclanrs/mg734/. It will return isDup = true
because the last option is has a time duplicate even though the name is different. Try removing that last option and isDup
will turn false
.
Upvotes: 1
Reputation: 8490
I think this would be very JQuery-ish:
function checkInput() {
$selects = $('select');
numSelects = $selects.length;
numUnique = $.unique($selects.map(function(){return $(this).val()})).length;
if (numUnique < numSelects) {
window.alert("Duplicates!");
return false;
}
return true;
}
Upvotes: 1