/    Sign up×
Community /Pin to ProfileBookmark

how to check if a checkbox is checked out of an array of checkboxes?

hi guys,

I am using a php script where I am using an array of checkboxes. Now, i was trying to use a javascript function that will stop the user to go to next page if they dont check any checkboxes.

Here goes my php code:

echo ‘<form name=”form” method=”post” action=”updateLink.php”
onSubmit=”return validateForm(form);”>;

while($row=$connector->fetchArray($result)) {

echo ‘<p>
<input type=”checkbox” name=”C1[]” value=’.$row[‘link_id’].’>
<input name=”T’.$row[‘link_id’].'” type=”text” size=”20″ value= “‘.$row[‘link’].'”>
</p>
<input type=”hidden” name=”section” value=’.$section.’>
<br />
‘;

}
echo ‘<center> <input type=”submit” name=”update” value=”Update”> </form></center>’;

and here is my javascript funciton:

function validateForm(form)
{

// set var check_choice to false
var checkbox_choice = false;

// Loop from zero to the one minus the number of check boxes

for(i=0;i<form.C1.length;i++)

// If there was a selection made

if(form.C1.checked){

checkbox_choice = true;

}

// If there were no selections made display an alert box
if (!checkbox_choice)
{
alert(“Please check atleast one link.”)
return (false);
}

}

I am completely new to javascript, so i probably missing something with presenting the array thing properly in my function. But to get the length of an array you use C1.lentgh and not C1[].length, right?

What am i doing wrong?

to post a comment
JavaScript

15 Comments(s)

Copy linkTweet thisAlerts:
@Mr_JApr 19.2005 — Please try the following, change [B]formName[/B]to the name of your form

function validateForm(){

myForm=document.[B]formName[/B]

var checkbox_choice = false;

for(i=0;i<myForm.length;i++){

if(myForm.elements[i].type=="checkbox"&&myForm.elements[i].checked){

checkbox_choice = true;

}



}



if (!checkbox_choice){

alert("Please check at least one link.")

return false

}





}
Copy linkTweet thisAlerts:
@crazy_topu_yahoauthorApr 20.2005 — Hi there,

Thanks a lot for your help. But there is one little prob, I couldnot make your code work.

So, now as you suggested I changed my form name to : formName


echo '<form name="formName" method="post" action="updateLink.php"

onSubmit="return validateForm(form);">';



while($row=$connector->fetchArray($result)) {


echo '<p><input type="checkbox" name="C1[]" value='.$row['link_id'].'>

<input name="T'.$row['link_id'].'" type="text" size="20" value= "'.$row['link'].'">

</p>

<input type="hidden" name="section" value='.$section.'>

<br />

';


}

echo '<center> <input type="submit" name="update" value="Update"> </form></center>';


and here is the java function you wrote: Are you sure, there wouldnot be any parameter inside the parantheses? something like validateForm(form)?

function validateForm(){



myForm=document.formName

var checkbox_choice = false;

for(i=0;i<myForm.length;i++){

if(myForm.elements[i].type=="checkbox"&&myForm.elements[i].checked){

checkbox_choice = true;

}



}



if (!checkbox_choice){

alert("Please check at least one link.")

return false

}





}





Many thanks in advance
Copy linkTweet thisAlerts:
@Mr_JApr 20.2005 — I do not yet know anything about php but I think it is the "form" inside the parentheses that is the problem

I reconstructed your code omitting the php and the parentheses "form" and it worked ok so I am assuming it will be the same when you put your php back in.

Try the following again


[SIZE=1]

<form name="formName" method="post" action="updateLink.php" onSubmit="return validateForm()">



<p><input type="checkbox" name="C1[]" value='.$row['link_id'].'>

<p><input type="checkbox" name="C1[]" value='.$row['link_id'].'>

<p><input type="checkbox" name="C1[]" value='.$row['link_id'].'>

<p><input type="checkbox" name="C1[]" value='.$row['link_id'].'>

<p><input type="checkbox" name="C1[]" value='.$row['link_id'].'>

<input name="T'.$row['link_id'].'" type="text" size="20" value= "'.$row['link'].'">

</p>

<input type="hidden" name="section" value='.$section.'>

<br />



<center> <input type="submit" name="update" value="Update">

</form>

</center>





<script>

function validateForm(){



myForm=document.formName



var checkbox_choice = false;



for(i=0;i<myForm.length;i++){



if(myForm.elements[i].type=="checkbox"&&myForm.elements[i].checked){

checkbox_choice = true;

}



}



if (!checkbox_choice){

alert("Please check at least one link.")

return false

}





}

</script>



[/SIZE]
Copy linkTweet thisAlerts:
@crazy_topu_yahoauthorApr 20.2005 — Yah, your code is just working fine now........I will find out what is stopping it from working properly inside PHP.

Hey, You have been really so helpful...thanks a ton! Planning to visit your country this year! ?


Oh there was another little prob giving me enough headache....you know, when the page loads i want the text field and textarea in disabled state and only when user checks the checkbox(es) they become enabled. I tried something like this:

As long as you make one selection, it works fine..but when the page first loads up, the text area remains in enabled state. instead of onClick can i use onPageLoad?



<html>

<head>

<title>Enable / Disable</title>

<script>

function SetState(obj_checkbox, obj_textarea)

{

if(!obj_checkbox.checked)
{
obj_textarea.disabled = true;
}


if(obj_checkbox.checked)
{
obj_textarea.disabled = false;
}

}

</script>

</head>

<body>


<form>

<input name="c1" type="checkbox" onClick="SetState(this.form.c1,this.form.my_text)"><br>

<textarea name="my_text">name:Arsen Yeremin</textarea>

<br>

</form>

</body>

</html>
Copy linkTweet thisAlerts:
@scragarApr 20.2005 — <script>

document.forms[0].my_text.disabled = true;

</script>
Copy linkTweet thisAlerts:
@crazy_topu_yahoauthorApr 20.2005 — Yah, but where to put the snippet? inside the function?
Copy linkTweet thisAlerts:
@scragarApr 20.2005 — it just goes at any point after the form closes(but still inside of the HTML!!)
Copy linkTweet thisAlerts:
@crazy_topu_yahoauthorApr 20.2005 — thanks? working now
Copy linkTweet thisAlerts:
@crazy_topu_yahoauthorApr 20.2005 — Mr J, you were right, the "form" inside the parentheses is the problem. ? working just fine now
Copy linkTweet thisAlerts:
@crazy_topu_yahoauthorApr 20.2005 — Hi,

When my user clicks submit button, I want all my checkboxes get clicked, so my php file can work with those selected checkboxes.


I done a little modification on your code, It should work just fine...but it's not working..what am i doing wrong....sorry, this javascript thing is still not quite clear to me...and hence, i m giving you guys so much trouble..but, that's the only think i would need now....nothing more this time ?


<script>

function checkBox(){

myForm=document.formName


for(i=0;i<myForm.length;i++){


if(myForm.elements[i].type=="checkbox"&&myForm.elements[i].unchecked){

Form.elements[i].checked;



}



}







}

</script>





</head>

<body>

<form name="formName" method="post" action="updateLink.php" onSubmit="return checkBox()">



<p><input type="checkbox" name="C1[]" value=''>

<p><input type="checkbox" name="C1[]" value=''>

<p><input type="checkbox" name="C1[]" value=''>

<p><input type="checkbox" name="C1[]" value=''>

<p><input type="checkbox" name="C1[]" value=''>



</p>







<center> <input type="submit" name="update" value="Update">

</form>

</center>
Copy linkTweet thisAlerts:
@UltimaterApr 20.2005 — When refering to an element with a name such as name="C1[]", the brackets are part of the name.

Also, whenever two elements have the same name, they are turned into an array.
[code=html]
<form name="formName">
<p><input type="checkbox" name="C1[]" value=''>
<p><input type="checkbox" name="C1[]" value=''>
<p><input type="checkbox" name="C1[]" value=''>
<p><input type="checkbox" name="C1[]" value=''>
<p><input type="checkbox" name="C1[]" value=''>
</form>

<script type="text/javascript">
alert(document.formName["C1[]"][0].checked)
alert(document.formName["C1[]"][1].checked)
</script>
[/code]
Copy linkTweet thisAlerts:
@crazy_topu_yahoauthorApr 20.2005 — I cant just do that..i mean referring each checkbox by its index; i.e. 0,1,2... etc. It is because, the checkboxes are being created on the fly upon user interaction, so inside a while loop in my php script i am creating them. The number of checkboxes could be 1 to unlimited, and for a programming issue, I must keep the name of each checkboxes same, which is C1[] here.

Now, doing the work as you have shown, wouldnot help much since you are referring each checkboxes with its index.....and I cant use index in my php [it's my own limitation, not PHP's]
Copy linkTweet thisAlerts:
@Mr_JApr 20.2005 — Replace this line

if(myForm.elements[i].type=="checkbox"&&myForm.elements[i].unchecked){

Form.elements[i].checked;

}





with



if(myForm.elements[i].type=="checkbox" && !myForm.elements[i].checked){

Form.elements[i].checked=true

}



On a side note you could still reference the checkboxes by name which means only the checkboxes named C1[] would be affected.



for(i=0;i<document.forms["formName"].length;i++){

if(document.forms["formName"].elements[i].name=="C1[]"&&!document.forms["formName"].elements[i].checked){

myForm.elements[i].checked=true

}

}
Copy linkTweet thisAlerts:
@UltimaterApr 20.2005 — I don't even know why you are using brackets in your element names at all...

Instead of [color=royalblue]name="C1[]"[/color] why not change it to: [color=royalblue]name="C1"[/color] ?

As long as two elements have the same name, their name is automaticly turned into an array -- w/o adding brackets to their name.
Copy linkTweet thisAlerts:
@Mr_JApr 20.2005 — On another side note, even if the checkboxes are generated on the fly you should still be able to reference them once they have been created like so


document.forms["formName"].elements["C1[]"].length
×

Success!

Help @crazy_topu_yaho spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...