mckeegan375 Posted March 3, 2012 Share Posted March 3, 2012 Hi All! I was hoping someone could help me with some simple JS form validation which involves a loop. So far, i have the following: <SCRIPT language=JavaScript> function validateForm() { var a = document.getElementsById('totalpayment'); var b = document.getElementsById('netpay'); for(var k=0;k<b.length;k++){ var c = a[k] var d = b[k] if (c.value > d.value) { alert("Total payment cannot be greater than net pay"); return false; } } } </script> My form has a loop which pulls data from a mysql database and it contains the fields 'totalpayment' and 'netpay' yet the validation does not display the alert if the total payment entered is greater than the net pay. Any help would be much appreciated. Cheers Andy Link to comment https://forums.phpfreaks.com/topic/258188-javascript-validation/ Share on other sites More sharing options...
joe92 Posted March 3, 2012 Share Posted March 3, 2012 var a = document.getElementsById('totalpayment'); //it's getElementById, notice the lack of s var b = document.getElementsById('netpay'); This is invalid. You cannot grab multiple elements by ID. What you need to use is getElementsByClassName and attach the relevant class to the elements you wish to check. Hope that helps you, Joe Link to comment https://forums.phpfreaks.com/topic/258188-javascript-validation/#findComment-1323473 Share on other sites More sharing options...
Adam Posted March 3, 2012 Share Posted March 3, 2012 getElementsByClassName() is not supported in IE before version 9, so you need to define a manual implementation when it doesn't exist as a back-up. Link to comment https://forums.phpfreaks.com/topic/258188-javascript-validation/#findComment-1323552 Share on other sites More sharing options...
joe92 Posted March 3, 2012 Share Posted March 3, 2012 That's a good point, one that I should have remembered to mention. http://lawrence.ecorp.net/inet/samples/js-getelementsbyclassname.shtml The one in the link above works like a charm. Joe Link to comment https://forums.phpfreaks.com/topic/258188-javascript-validation/#findComment-1323556 Share on other sites More sharing options...
mckeegan375 Posted March 3, 2012 Author Share Posted March 3, 2012 Thanks for all your help guys! Joe, i used the link you posted for my solution Cheers Andy Link to comment https://forums.phpfreaks.com/topic/258188-javascript-validation/#findComment-1323560 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.