JavaScript Data Validation Radio Buttons


Radio buttons must exist in groups. Each group of radio buttons will have only one button active. The group should be set up so one button is active at the very beginning, so there is always exactly one active button in the group. Each button will have a unique id, but all of the buttons in the group will have the same name. The name attribute is used to indicate the group of radio buttons. The browser recognizes this behavior, and automatically deselects the other buttons in the group whenever one is selected. It’s important to preset one of the radio buttons to true with the checked = “checked” attribute. If you fail to do so, you’ll have to add code to account for the possibility that there is no answer at all. This post is based on the code in Chapter 7 of the book JavaScript and AJAX for Dummies.

With what weapon will you fight the dragon?








Below is the HTML for the radio buttons you see above:

<h4>With what weapon will you fight the dragon?</h4>
<form action = "">
<fieldset>
	<input type = "radio"
		name = "weaponDragon"
		id = "radSpoon"
		value = "spoon"
		checked = "checked" />
	<label for = "radSpoon">Spoon</label>
	<input type = "radio"
		name = "weaponDragon"
		id = "radFlower"
		value = "flower" />
	<label for = "radSpoon">Flower</label>
	<input type = "radio"
		name = "weaponDragon"
		id = "radNoodle"
		value = "wet noodle" />
	<label for = "radNoodle">Wet Noodle</label>
	<button type = "button"
	onclick = "fight()">
	fight the dragon
	</button>
</fieldset>
</form>
<div id = "outputRadioDragon">
</div>

Here is the JavaScript code:

function fight(){
	var weapon = document.getElementsByName("weaponDragon");
	for (i = 0; i < weapon.length; i++){
		currentWeapon = weapon[i];
		if (currentWeapon.checked){
			var selectedWeapon = currentWeapon.value;
		} 
	} 
	var outputRD = document.getElementById("outputRadioDragon");
	var response = "<h3>You defeated the dragon with a ";
	response += selectedWeapon + "<\/h3> \n";
	// put the text and HTML tags into the div tag
	// that has the id=outputRadioDragon
	outputRD.innerHTML = response;
} 

Just as a reminder, below is the WordPress Enqueque code that registers and loads the JavaScript we wrote.

function pw_radio_buttons_dragon_script() {
	wp_register_script('my_radio_buttons_dragon_script', get_stylesheet_directory_uri() . '/radioButtonsDragonJSDataValidation.js', false,'1.0', true);
	wp_enqueue_script('my_radio_buttons_dragon_script');
}
add_action( 'wp_enqueue_scripts', 'pw_radio_buttons_dragon_script' );

Leave a comment

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