Need help to check several checkboxes

Discussion in 'JavaScript' started by fredi88, Sep 2, 2006.

  1. #1
    Hi,

    I am newbie to all this and I really appreciate all the help out there

    I have a form with 4 checkboxes.

    I need atleast one of them to be checked before being able to post the form

    How can I do this?

    This is my simple form
    ---------------------------
    <form name="form1" method="post" action="nextpage.htm" target="_blank">
    <p>
    <input name="checkbox2" type="checkbox" id="checkbox2" value="1">
    Number 1</p>
    <p>
    <input name="checkbox2" type="checkbox" id="checkbox2" value="2">
    Number 2</p>
    <p>
    <input name="checkbox3" type="checkbox" id="checkbox3" value="3">
    Number 3</p>
    <p>
    <input name="checkbox4" type="checkbox" id="checkbox4" value="4">
    Number 4</p>

    <input name="Submit" type="submit" >

    _--------------------------------------------

    Thanks for your help
    Fred
     
    fredi88, Sep 2, 2006 IP
  2. themole

    themole Peon

    Messages:
    82
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You shouldn't let javascript be your only form of validation. I could turn javascript off and I wouldn't have to check any of them then. :)

    That being said, this should work for you:

    
    
    <script>
    
    function validate_check_boxes()
    {
    	var success;
    
    	if(document.form1.checkbox1.checked)
    		success = 1;
    	else if(document.form1.checkbox2.checked)
    		success = 1;
    	else if(document.form1.checkbox3.checked)
    		success = 1;
    	else if(document.form1.checkbox4.checked)
    		success = 1;
    	else
    		success = 0;
    
    	if(success == 1)
    		return true;
    
    	else
    	{
    		document.getElementById('error').innerHTML = "Error! At least one checkbox must be checked!";
    		return false;
    	}
    
    }
    
    
    </script>
    
    <span id='error'></span>
    <form name="form1" method="post" action="nextpage.htm" onsubmit="return validate_check_boxes()">
    <p>
    <input name="checkbox1" type="checkbox" id="checkbox1">
    Number 1 </p>
    <p>
    <input name="checkbox2" type="checkbox" id="checkbox2" >
    Number 2 </p>
    <p>
    <input name="checkbox3" type="checkbox" id="checkbox3">
    Number 3 </p>
    <p>
    <input name="checkbox4" type="checkbox" id="checkbox4">
    Number 4 </p>
    
    <input name="Submit" type="submit">
    </form>
    
    
    Code (markup):
    -the mole
     
    themole, Sep 3, 2006 IP
  3. fredi88

    fredi88 Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Many Thanks

    In the nextpage.htm, I actually use php to make sure that one checkbox has been selected, with an error message if this is not the case. I just needed something on the initial page for ease of use for the person browsing

    Fred:)
     
    fredi88, Sep 3, 2006 IP