Reputation: 262
I used to validate checkbox form with a code like this:
<div>
<form action="survey.php" method="post" name="survey">
<span class="form"><input type="checkbox" name="event1" onClick="return countMarketing()">Event1</span>
<span class"form"><input type="checkbox" name="event2" onClick="return countMarketing()">Event2</span>
<span class"form"><input type="checkbox" name="event3" onClick="return countMarketing()">Event2</span>
<!-- other forms -->
</form>
</div>
And a javascript validation that is something like this (to limit the count of checkboxes checked):
function countMarketing() {
var NewCountMarketing = 0
if (document.survey.event1.checked)
{NewCountMarketing = NewCountMarketing + 1}
if (document.survey.event2.checked)
{NewCountMarketing = NewCountMarketing + 1}
if (document.survey.event3.checked)
{NewCountMarketing = NewCountMarketing + 1}
if (NewCountMarketing == 3)
{
alert('Please choose only two')
document.survey; return false;
}
}
And validation like this works. But now, say im using php to for the submission, how do i check if in JS if the name of the form is something like this:
<input type="checkbox" name="events[]" id="event1" onClick="return countMarketing()">Event1
Ive tried to change the JS to:
if (document.survey.events[].checked)
{code here}
if (document.survey.getElementByName('events[]').checked)
{code here}
if (document.survey.getElementById('event1').checked)
{code here}
But it doesnt work.. any can shed some light on me about this? thank you very much :)
Upvotes: 0
Views: 226
Reputation: 55750
First remove the inline events declaration
and move it to an external Javascript file
or a script block
You can always use bracket Notation
to access such attributes
document.survey["events[]"]
Code
var elems = document.survey,
checkboxNames = ["event1[]", "event2[]", "event3[]"];
for (var i = 0; i < checkboxNames.length; i++) {
bindClick(elems[checkboxNames[i]]);
}
function bindClick(elem) {
elem.addEventListener('click', countMarketing);
}
function countMarketing() {
var NewCountMarketing = 0
var latest;
for (var i = 0; i < checkboxNames.length; i++) {
if (elems[checkboxNames[i]].checked) {
latest = elems[checkboxNames[i]];
NewCountMarketing++;
}
}
if (NewCountMarketing == 3) {
latest.checked = false;
alert('Please choose only two')
document.survey;
return false;
}
}
Upvotes: 1
Reputation: 4021
If you are in fact using jQuery you could do:
Make sure you are including jQuery in your document before you use this function & that the document is loaded before you try to run the function.
function countMarketing() {
if( $('input[name="events[]"]').filter(':checked').length > 2 ) {
alert('Please choose only two');
}
}
Upvotes: 1