PDA

View Full Version : Javascript Help


Tascha
02-08-2005, 02:34 PM
Hi there,

I have a set of 6 boxes, for rental period and then a rental cost respectively, and these are named : rentperiod2 - rentcost2, then rentperiod3 - rentcost3, etc. through to 6. (rentperiod1 is not included as this has another separate checker on it)

Basically I want to reduce the repetitive code (I have inlcluded this example CODE A) which I have to put in 5 times, to a FOR LOOP (which I also include below CODE B), with an incremental numeric variable "y" to go through the boxes, but it seems to screw up my whole javascript... and just doesnt work, this is really driving me mad, is there any obvious reasons or things I am doing wrong?? Any help would be soo appreciatedddd :o).


CODE A

if (document.addProp.rentperiod2.value !== "" && document.addProp.rentcost2.value == "") {
alertMessage += "<strong>Rental Period Cost 2 :</strong> You have entered a Rental Period 2, you need to enter a Cost value for this<br>";
document.addProp.rentcost2.focus();
}

I have this 5 times for each box from 2 - 6

CODE B ( Doesnt work )

for(var y = 2; y < 6; y++) {
if (document.addProp.rentperiod(y).value !== "" && document.addProp.rentcost(y).value == "") {
alertMessage += "<strong>Rental Period Cost 2 :</strong> You have entered a Rental Period " + y + ", you need to enter a Cost value for this<br>";
document.addProp.rentcost(y).focus();
}
}

Badman3k
02-08-2005, 05:23 PM
Hey and welcome to CF:thumbsup:,

I haven't had chance to test this but I think it'll work. Try this:

for(var y = 2; y < 6; y++) {
if (document.addProp.rentperiod+y+.value !== "" && document.addProp.rentcost+y+.value == "") {
alertMessage += "<strong>Rental Period Cost 2 :</strong> You have entered a Rental Period " + y + ", you need to enter a Cost value for this<br>";
document.addProp.rentcost+y+.focus();
}
}


If not let me know and I'll work on it :thumbsup:

Badman3k
02-08-2005, 05:38 PM
Okay that was rubbish, I've just tested it :o lol:D

This does work, and should do exactly what you want it to do :thumbsup:


for (y=2; y <= 6; y++){
if (document.addProp['rentperiod'+y].value !== "" && document.addProp['rentcost'+y].value == "") {
alertMessage += "<strong>Rental Period Cost 2 :</strong> You have entered a Rental Period " + y + ", you need to enter a Cost value for this<br>";
document.addProp['rentcost'+y].focus();
}
}


Hope that helps :)

Tascha
02-08-2005, 08:26 PM
Thank you soooooo much for your help, it worked perfectly :thumbsup: :D :D :D