Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Comparing and validating numbers in a web form 1

Status
Not open for further replies.

Katie6

Programmer
Jun 12, 2007
58
0
0
GB
Hi there, I have created a web form with the following fields laid out as below:

Field 1a and Field 1b
Field 2a and Field 2b
Field 3a and Field 3b.

The user will fill in those fields with numbers to show how many pieces of information they have received and the total they asked for e.g.

5 of 6 (they received 5 bits of info of the 6 they asked for)
6 of 7
8 of 8

What I need is some javascript to give an error message if the user enters a higher number into Field a than Field b.

e.g. if the user enters 6 of 5, an error message should come up.

I am a complete novice when it comes to javascript, and I would be very grateful for any help any of you could give.

Many thanks,

Katie :)
 
Katie,
here you go...

Code:
function Validate(){
var 1a = document.getElementById('Field1').value;
var 1b = document.getElementById('Field2').value;
if(1a>1b){
alert('something is wrong'); 
document.getElementById('Field1').value = ''; //Clear field
}
}

you may however want to make this a bit more dynamic (like what I showed you the other day i.e. pass in the elements ID's using the onchange event and calling the function with (this.id)

Cheers

Nick
 
Actually I'm going to give you an example of what I mean above!

Code:
function Validate(Field1,Field2){
var Value1 = document.getElementById(Field1).value;
var Value2 = document.getElementById(Field2).value;

if(Value1 > Value2){
alert('something is wrong'); 
document.getElementById(Field1).value = '';
}
}

and your html should look something like this:

Code:
<input type="text" id="1a" onchange="Validate('1a','1b');">
<input type="text" id="1b">

This way you can re-use your javascript function...

Cheers

Nick
 
Thank you so much for your help once again! Yes, I will try and make it dynamic from what I learnt from you last time. Actually, this is going to be part of the thing you sent me the other day, so I'm looking forward to seeing whether I can make them work together!

Katie
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top