JQuery way to handle select lists, radio buttons and checkboxes

When I process HTML form elements using jQuery, I always get an ugly combination of jQuery syntax and plain JavaScript, for example:

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 for handling typical operations on elements such as <select>, <input type="radio">and <input type="checkbox">?

With typical, I mean things like reading the value of the selected radio button in a group or replacing items in a select list. I did not find them in the documentation, but I admit that overloading the method can make the doc browser more difficult.

Update

Thanks to everyone. Once on the right track, I realized that the rest. For example, I can process the list <select>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>');
+3
5

, . :

<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
});

. http://api.jquery.com/category/selectors/form-selectors/ .

+8

, , .text() <option> ( :selected ), :

function doStuff($combo){
  var txt = $combo.children("option:selected").text();
  $combo.closest("div.item").find("input[name$=\[description\]]").val(txt);
}

<option value="4" selected>Four</option>, .val(), :

var val = $combo.val();
+5

<select> ( .val()). :

$('input:radio[name=whatever]:checked').val()

:

$('#checkboxId:checked').val()

, ( - , ).

edit . ( .text() .val()).

+3

val(). val() .

:checked.

, jQuery: http://api.jquery.com/val/

0

Select ( .val()). radio buttons :

$('input:radio[name=whatever]:checked').val()

:

$('#checkboxId:checked').val()

, ( - , ).

edit . ( .text() .val()).

Ignore formatting .... I did not do this ..;)

0
source

Source: https://habr.com/ru/post/1746410/


All Articles