JavaScript Data Validation Check Boxes

Any time you have Boolean data, if some value can be true or false, an HTML check box is a good tool. Check boxes are independent of each other. Build your HTML, always being sure to use id’s. Be sure your id’s are descriptive and unique. For example, avoid using an id such as output. Your button will have an onclick event that is a JavaScript function. That function will be in JavaScript file on your server. Here in WordPress land we used the WordPress function enqueue() to register and load the JavaScript file.

What do you want on your pizza?

Your order:

Here is the HTML:

<h3>What do you want on your pizza?</h3>
<form action = "">
	<input type = "checkbox"
	id = "chkPepperoni"
	value = "pepperoni" />
	<label for = "chkPepperoni">Pepperoni</label>
	<input type = "checkbox"
	id = "chkMushroom"
	value = "mushrooms" />
	<label for = "chkMushroom">Mushrooms</label>
	<input type = "checkbox"
	id = "chkSausage"
	value = "sausage" />
	<label for = "chkSausage">Sausage</label>
	<button type = "button"
	onclick = "porterwebsites_check_boxes_pizza_script()">
	Order Pizza 
<h4>Your order:</h4>
<div id = "pizzaoutput">

Here is the JavaScript:

function porterwebsites_check_boxes_pizza_script(){
	//get variables
	alert("Hi pizza lover.");
	var toppingsChosen = false;
	var chkPepperoni = document.getElementById("chkPepperoni");
	var chkMushroom = document.getElementById("chkMushroom");
	var chkSausage = document.getElementById("chkSausage");
	var outputpizza = document.getElementById("pizzaoutput");
	var resultout = "<ul> \n"  // innerHTML can contain markup!
	if (chkPepperoni.checked){
		resultout += "<li>" + chkPepperoni.value + "<\/li>\n";
		toppingsChosen = true;
	if (chkMushroom.checked){
		resultout += "<li>" + chkMushroom.value + "<\/li>\n";
		toppingsChosen = true;
	if (chkSausage.checked){
		resultout += "<li>" + chkSausage.value + "<\/li>\n";
		toppingsChosen = true;
	resultout += "<\/ul>\n"
	outputpizza.innerHTML = resultout;
	if (toppingsChosen) {
		alert("Good choice! Expect a knock at your door.")
	} else {
		alert ("Cheese pizza ordered! See you soon.")

Leave a comment

Your email address will not be published. Required fields are marked *