SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    38911 Basic Bytes Free johnuk's Avatar
    Join Date
    Jul 2008
    Location
    Somerset, England
    Posts
    458
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Iterate Checkbox values with JS ?

    I have some checkboxes on a form like this: -

    Code HTML4Strict:
    <form id="EventForm" name="EventForm" method="post">
     <input name="EventRecur[]" type="checkbox" class="checkbox" value="EveryDay" />
     <input name="EventRecur[]" type="checkbox" class="checkbox" value="Monday" />
     <input name="EventRecur[]" type="checkbox" class="checkbox" value="Tuesday" />
    </form>

    Basically im trying to get the selected values with JS, but im getting the error "document.EventForm.EventRecur is undefined"

    My JS looks like this: -

    Code JavaScript:
    function previewMessage()
    {
    	function get_check_value()
    	{
    		var c_value = "";
    		for (var i=0; i < document.EventForm.EventRecur.length; i++)
    	    {
    		    if (document.EventForm.EventRecur[i].checked)
    			{
    				c_value = c_value + document.EventForm.EventRecur[i].value + "\n";
    			}
    	   }
    	}
    	alert(get_check_value());
    	//Display Submit Button
    	document.getElementById("submit_button").style.display = "inline";
    }

    Any ideas where im going wrong? Is it because the field input names are arrays? e.g. EventRecur[]?

    Many thanks!

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,683
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    The form name is "EventRecur[]" so that's what you need to use in your script.

    Code javascript:
    for (var i=0; i < document.EventForm."EventRecur[]".length; i++)

    It's only with PHP that the square brackets allow the form field to be treated as if it were an array, not JavaScript.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •