Forms
Knowing how to handle forms is an essential skill in web development. In this lesson we'll learn how to work with form fields.
Retrieving the value of a field
Earlier in the course we've learned how to get the value from input fields unsing the value property. Now let's see how to get the vaues of different types of fields.
Select Box
Show the selected options here:
document.getElementById("show_option").onclick = function () {
var selectField = document.getElementById("options");
var selectedOption = selectField.options.selectedIndex;
var selectedValue = selectField.options[selectedOption].innerHTML;
document.getElementById("selected_option").innerHTML = selectedValue;
};
There's an easy way of doing this, since select boxes have a value property that stores the value of the selected option. However with this method we can only get the value, not the inner html.
var selectedOption = document.getElementById("options").value;
console.log(selectedOption);
Besides getting the selected valur from a select box, we can also use Javascript to force the selection of an option. We do this by defining the value attribute.
document.getElementById('options').value = "opt3";
Radio Buttons
Show the selected option:
document.getElementById("show_radio").onclick = function () {
var radio = document.getElementsByName("gender");
var radio_selected;
for (var a = 0; a < radio.length; a++) {
if (radio[a].checked) {
radio_selected = radio[a].value;
}
}
document.getElementById("selected_radio").innerHTML = radio_selected;
};
CheckBoxes
Show a list of the selected options:
document.getElementById("Show_check").onclick = function () {
var check = document.getElementsByName("interest");
document.getElementById("selected_check").innerHTML = "";
for (var b = 0; b < check.length; b++) {
if (check[b].checked) {
document.getElementById("selected_check").innerHTML += '<li>' + check[b].value + '</li>';
}
}
};