PDA

View Full Version : Simple logic problem


Spudhead
09-11-2002, 05:06 PM
Hi,

It's 5pm and I'm having difficulty thinking in straight lines.

I've got 6 select boxes:

startDay
startMonth
startYear
endDay
endMonth
endYear

on a form, amongst other bits. Their value can be either "-" or a number. Default is "-".

Problem is simply validating this: a user should allowed to complete either none of them, or all six. Two is no good. Three is right out. Sorry, sudden Monty Python attack.

Could someone demonstrate how, using a combination of loops, "if" statements and... actually, whatever you want... this might be achieved?

Ta.

beetle
09-11-2002, 06:02 PM
Sure. <script>
var selIDs = new Array('startDay','startMonth','startYear','endDay','endMonth','endYear');
var defChar = "-";

function checkDates(f) {
var values = new Array();
for (var i=0; i<selIDs.length; i++)
values[i] = f.elements[selIDs[i]].options[f.elements[selIDs[i]].selectedIndex].value;
var placeholder = values[0];
for (i=1; i<values.length; i++)
if ((placeholder == defChar && values[i] != placeholder) || (placeholder != defChar && values[i] == defChar)) {
alert("You must make a selection for all dates or for none");
return false;
}
return true;
}
</script>

<form onSubmit="return checkDates(this);">

Spudhead
09-12-2002, 11:35 AM
Ah. I like what you've done here. :)

Thanks very much, works like a dream. For some reason it didn't occur that I could use just one of the form values to check the rest - I envisaged checking every value against every other value in some torturously complex multiple-embedded loop... but anyway. Cheers!

beetle
09-12-2002, 01:25 PM
:D

No problem. Sometimes a 2nd set of eyes is the best solution ;)