1. Post #1
    Airport Dweller
    Slater's Avatar
    October 2005
    1,197 Posts
    Hey all, thanks for taking your time to read this.

    I'm stumped with my JavaScript validation here, I don't know why my code won't work. The object, is to loop through a list of books (name, isbn, price) using PHP and print them to a page. That's fine. Each one of them is echo'd and working with a checkbox each.

    I now want to validate it, to point out that there are no books checked on form submission.

    I've used a NAME tag to give each checkbox a reference, this is book[].

    Code:
        var isChecked = false; 
        
        for (var i = 0; i < document.orderForm.book.length; i++)
        {
            if (document.orderForm.book[i].checked)
            {
                isChecked = true; 
            }        
            
            else 
            {
                alert("Please select at least one book.");
                valid = false;
            }
        }
    Related PHP:
    Code:
    echo "\t<div class='item'>
    <span class='chosen'><input type='checkbox' name='book[]' value='{$book['bookISBN']}' title='{$book['bookPrice']}' /></span>
    <span class='bookTitle'>{$book['bookTitle']}</span>
    <span class='bookYear'>{$book['bookYear']}</span>
    <span class='catDesc'>{$book['catDesc']}</span>
    <span class='bookPrice'>{$book['bookPrice']}</span>
    </div>\n";
    echo "<hr/>";
    }
    I know it's going to be something really stupid on my part, so I'm bracing myself for it.

  2. Post #2

    May 2011
    213 Posts
    Try changing "document.orderForm.book" to "document.orderForm.getElementsByName('book')"
    Reply With Quote Edit / Delete Reply Windows 7 United Kingdom Show Events Agree Agree x 1 (list)

  3. Post #3
    Airport Dweller
    Slater's Avatar
    October 2005
    1,197 Posts
    I've played around a little with your suggestion, but I can't seem to get it to run. Firebug isn't flagging anything up either.

    Any other ideas?

  4. Post #4
    rookwood101's Avatar
    September 2011
    252 Posts
    document.orderForm.book.length change that to document.orderForm.book.value.length

  5. Post #5
    Airport Dweller
    Slater's Avatar
    October 2005
    1,197 Posts
    Still doesn't work. Thanks for trying. I'm truly stumped with this one.

  6. Post #6
    Still doesn't work. Thanks for trying. I'm truly stumped with this one.
    I'll re-create it today and see if I can't figure it out!
    Reply With Quote Edit / Delete Reply Windows 7 United States Show Events Winner Winner x 1 (list)

  7. Post #7
    hzy
    Gold Member
    hzy's Avatar
    January 2009
    1,943 Posts
    put your html/js up on here: http://jsfiddle.net/ it makes it much easier for people to help you.
    Reply With Quote Edit / Delete Reply Mac Australia Show Events Agree Agree x 2 (list)

  8. Post #8
    Figured it out... Here is my complete test.php script that I wrote.

    All you need to do is change your Javascript code for selecting the form elements to:

    document["FORMNAME"]["books[]"]

    Because of the [] that PHP requires to get an array from the post data, Javascript thinks that the actual name of those form elements is "book[]", so you can't use "book" to access them. And of course we can't just write document.formname.book[][i].length because that confuses it even more.

    So just use the other way of getting around DOM in Javascript using [""][""] and now because "book[]" is in quotes, it recognizes it as a valid name.

    Code:
    <?php
    
    if (isset($_POST["book"])) {
    	foreach ($_POST["book"] as $key => $value) {
    		echo $value . ", ";
    	}
    }
    
    ?>
    
    <!DOCTYPE html>
    <html>
    	<head>
    		<title>Testing Bay</title>
    		<script type="text/javascript">
    
    			function ValidateForm() {
    				
    				var isChecked = false; 
    				    
    				if (document["orderForm"]["book[]"]) {
    		   			if (typeof document["orderForm"]["book[]"].length != 'undefined') {
    		      			for (i = 0; i < document["orderForm"]["book[]"].length; i++) {
    		         			if (document["orderForm"]["book[]"][i].checked) {
    		            			isChecked = true;
    		        			}
    		      			}
    		   			} else {
    		      			isChecked = document["orderForm"]["book[]"].checked;
    		   			}
    		   			if (isChecked == false) {
    		   				alert("Please select at least one book!");
    		   			} else {
    		   				alert("At least one book was selected; you're good to go!");
    		   			}
    				}
    			}
    
    		</script>
    	</head>
    
    <body>
    
    <div style="width: 960px; margin:0 auto; background: #EEE; border: 1px solid #DDD;">
    	<form name="orderForm" method="post" action="test.php">
    		<input type="checkbox" name="book[]" value="book1" />Book 1
    		<input type="checkbox" name="book[]" value="book2" />Book 2
    		<input type="checkbox" name="book[]" value="book3" />Book 3
    		<button onclick="ValidateForm()" value="Test" name="TEST">
    	</form>
    </div>
    
    </body>
    </html>
    Reply With Quote Edit / Delete Reply Windows 7 United States Show Events Programming King Programming King x 2Winner Winner x 1 (list)

  9. Post #9
    Airport Dweller
    Slater's Avatar
    October 2005
    1,197 Posts
    Not going to lie here, I absolutley adore TheBigS right now. Tried and tested, works perfectly.
    Reply With Quote Edit / Delete Reply Windows 7 United Kingdom Show Events Winner Winner x 1Friendly Friendly x 1Agree Agree x 1 (list)

  10. Post #10
    Gold Member
    itsbth's Avatar
    March 2006
    214 Posts
    http://jsfiddle.net/gFGGw/

    Cleaner code. Does not work in IE < 9, as it uses addEventListener, but should work in all other major browsers (tested in Chrome (Chromium 18.0.1011.0), Firefox (Aurora 13.0a2), IE (9), Opera (11.62)).

  11. Post #11
    rookwood101's Avatar
    September 2011
    252 Posts
    Does not work in IE < 9
    Oh well that's alright only about a third of all browsers then.
    Reply With Quote Edit / Delete Reply United Kingdom Show Events Funny Funny x 1 (list)

  12. Post #12
    Gold Member
    itsbth's Avatar
    March 2006
    214 Posts
    Oh well that's alright only about a third of all browsers then.
    http://jsfiddle.net/gFGGw/5/
    Only got IE9 here, so I haven't tested it, but it should work.