jQuery way to handle select lists, radio buttons and checkboxes

html, javascript, jquery

Solution

Yes, you should be able to simplify your code a lot. Here are a few examples of working with form elements:

`<input type="text">`

$(':text') // select all text boxes
$('input#example').val(); // gets value of a text box

`<input type="checkbox">`

$(':checkbox') // selects all checkboxes
$('input.example:checked') // selects all ticked checkboxes with class 'example'
$('#example').is(':checked'); // true if checkbox with ID 'example' is ticked

`<input type="radio">`

$(':radio') // selects all radio buttons
$(':radio:checked').each( function() {
    $(this).val(); // gets value of each selected radio button
});
$('input:radio[name="asdf"]'); // gets particular group of radio buttons

`<select>`

$('select#example').change( function() {
    // this part runs every time the drop down is changed
    $(this).val(); // gets the selected value
});

See also http://api.jquery.com/category/selectors/form-selectors/ for more selectors.

Problem

When I handle HTML form elements with jQuery, I always end up with an ugly mix of jQuery syntax and plain JavaScript like, e.g.: ``` function doStuff($combo){ if( $combo.get(0).options[$combo.get(0).selectedIndex].value=="" ){ var txt = ""; }else{ var txt = $combo.get(0).options[$combo.get(0).selectedIndex].text; } var $description = $combo.closest("div.item").find("input[name$=\[description\]]"); $description.val(txt); } ``` Are there standard jQuery methods to handle typical operations on elements like `<select>`, `<input type="radio">` and `<input type="checkbox">`? With typical, I mean stuff like reading the value of the selected radio button in a group or replacing elements in a selection list. I haven't found them in the documentation but I admit that method overloading can make doc browser kind of tricky. Update Thanks everyone. Once in the right track, I figured out myself the rest of the stuff. E.g., I can handle a `<select>` list like any other DOM tree: ``` $("select") .empty() .append('<option value="">(Pick one)</option><option value="a">Option A</option><option value="b">Option B</option>'); ```

Original source