Page 1 of 1

[SOLVED] Check the same value

Posted: Wed Jun 08, 2005 10:57 pm
by S_henry
Lets say i have 3 textboxes in page A. Before i submit this page, i want to check all the textboxes' value to make sure all the values are different. If there are only 3 textboxes, i can code it like this:

Code: Select all

if(($txtA == $txtB)||($txtA == $txtC)||($txtB == $txtC))
{
   echo &quote;The value should be different from each other.&quote;;
}
But if there are many textboxes (eg. 30), how to make the (best) checking? Anybody can help me pls?

Posted: Wed Jun 08, 2005 11:29 pm
by Burrito
you say "before" you submit the page...if that's the case you'll need js and this should have been posted in the client side forum.

if that is indeed what you intended, this should work for you:

Code: Select all

<html>
<head>
	<title>Untitled</title>
<script>
function checkIt(){
	for(var i=1;i<=4;i++){
		t1 = &quote;text&quote;+i;
		t2 = document.MyForm(t1);
			for(var j=1;j<=4;j++){
				s1 = &quote;text&quote;+j;
				s2 = document.MyForm(s1);
				if(t2.name !== s2.name){
					if(t2.value == s2.value){
						alert(&quote;something is the same&quote;);
						return false;
					}
				}
			}
	}

}
</script>
</head>

<body>
<form name=&quote;MyForm&quote; onSubmit=&quote;return checkIt()&quote;>
<input type=&quote;text&quote; name=&quote;text1&quote;>
<input type=&quote;text&quote; name=&quote;text2&quote;>
<input type=&quote;text&quote; name=&quote;text3&quote;>
<input type=&quote;text&quote; name=&quote;text4&quote;>
<input type=&quote;submit&quote; value=&quote;check&quote;>
</form>


</body>
</html>

Posted: Thu Jun 09, 2005 12:33 am
by Syranide
One thing you have to be careful about is to not check each one against every single one, as that would give you an exponential growth, meaning that with 100 boxes you would do 10000 tests.

A very simple solution is to store each of the values in an array, with the value as the key, and just anything as the value. Then checking the length of the array against the number of checkboxes. This ensures that it is has a linear behaviour at most times. (Also, note that if you name the checkboxes val[0] val[1] etc, you could just flip the val-array and you have your array.

Posted: Thu Jun 09, 2005 12:56 am
by Burrito
Syranide wrote:One thing you have to be careful about is to not check each one against every single one, as that would give you an exponential growth, meaning that with 100 boxes you would do 10000 tests.

A very simple solution is to store each of the values in an array, with the value as the key, and just anything as the value. Then checking the length of the array against the number of checkboxes. This ensures that it is has a linear behaviour at most times. (Also, note that if you name the checkboxes val[0] val[1] etc, you could just flip the val-array and you have your array.
nice idea...me likey

Posted: Tue Jun 14, 2005 10:11 pm
by S_henry
OK. Thanx guys for the solutions. :)