0

Can any guru show me how to get values from HTML Form element - RADIO BUTTON and CHECK BOX?

For example in case of text box we can get the value directly by getElementById(id).value;

But how to get the value for a combo box (drop down menu), radio button and checkbox ?

Thanks.

2
  • Side note: pretty much no one does it this way anymore, and instead most people use frameworks like jQuery, Mootools, etc, so that we can just do $('#yourSelectId').val() or $('#yourSelectId option:selected').val() (jquery examples). Commented Jan 17, 2012 at 5:42
  • you can do a little googling and you will find 1000s of example. put a little effort. Commented Jan 17, 2012 at 5:50

2 Answers 2

2

Drop down (<select>):

var el = document.getElementById('yourSelectId');
var value = el.options[el.selectedIndex].value;

If you're treating your select list as a multi-select (combobox) list, you have to loop through the options and check if they are selected:

var el = document.getElementByid('yourSelectId');
var selectedValues = [];

for (var i = 0; i < el.options.length; i++) {
    if (el.options[i].selected) {
        selectedValues.push(el.options[i].value);
    }
}

// all selected values are now in the selectedValues array.

Radio buttons and checkboxes should also have value properties, but more appropriately I think I would only test whether they are checked:

var isChecked = document.getElementById('yourRadioOrCheckboxId').checked;
Sign up to request clarification or add additional context in comments.

1 Comment

el.options[el.selectedIndex].value can be simply el.value, unless you need to support really ancient browsers (NN4 and similar).
1

For checkbox, the element has a .checked property:

document.getElementById('foo').checked; // true or false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.