View Full Version : Changing CheckBox With a VAR [Should be Easy - Please Help]

02-25-2007, 07:04 PM
I tired to slim this down as much as I could..... I'm trying to make a function that will change the checkboxs that I pass to it..

<script type="text/javascript">
function checkBoxValidate(Engine_Var){
document.new_car_script.Engine_Var.checked = true;

The check box is named Engine3 and the variable is getting passed properly from an alert that I had in there. If I change Engine_Var to Engine3 it works.

Please Help - Jutboy

02-25-2007, 10:08 PM
hmmm.. try something like this.

function checkBoxValidate(Engine_Var){
var CheckboxElement = eval("document.new_car_script." + Engine_Var);
CheckboxElement.checked = true;

02-26-2007, 12:45 AM
Your the freaking man!!!!!

02-26-2007, 01:50 AM
haha... glad i could help and welcome to the board.

02-26-2007, 05:15 PM
eval method is not efficient and is confusing for new coders.
Try this instead:

function checkBoxValidate(Engine_Var){
document.new_car_script.elements[Engine_Var].checked = true;
I've used the javascript square bracket notation. See my sig for more info on this. This technique is very useful.

02-26-2007, 08:35 PM
whats not efficient about it? not saying your wrong, just courious. I've used it plenty without a problem.

02-27-2007, 07:58 PM
This has been discussed lengthily here in CF.


02-27-2007, 10:12 PM
Wow, this board is great....lots of info here

This is actually my code... I put in php so I could just loop it and save myself lots of time.....its designed for lots and lots of parts.

echo "<script type='text/javascript'>";
echo "function checkBoxValidate(part0,condition0,part1,condition1,part2,condition2,part3,condition3){";

for ($i=0;$i<=3;$i++){
echo "var CheckboxElement = eval('document.new_car_script.' + part$i + '[' + condition$i + ']');";
echo "CheckboxElement.checked = true;";

The thing is I couldn't get glenngv's method to work....seems js doesn't like you putting a variable/or combining variables/strings into a document command? i would like to be as efficent as possible however. Please advise.

Thanks - Jman

02-27-2007, 10:27 PM
echo "var CheckboxElement = document.new_car_script.elements[part$i][condition$i];";
I don't know php so I may have inserted the $i variable incorrectly.

02-27-2007, 11:04 PM
Your the man too!!!! You basically got it....

echo "var CheckboxElement = document.new_car_script.elements[part$i"."][condition$i"."];";
echo "CheckboxElement.checked = true;";

Hehe......Please notice I gave both of you rep points!