JS gets the select option text_value method

  • 2020-03-30 01:07:31
  • OfStack

HTML code:


<select id="month" onchange="selectInput(this)">
    <option  value="01">January</option>
    <option  value="02">February</option>
    <option  value="03">March</option>
    <option  value="04">April</option>
    <option  value="05">May</option>
    <option  value="06">June</option>
    <option  value="07">July</option>
    <option  value="08" selected="selected">August</option>
    <option  value="09">September</option>
    <option  value="10">October</option>
    <option  value="11">November</option>
    <option  value="12">December</option>
</select>

Get the value, text of the selected object in select with jQuery


$(function(){
    $("#month").change(function() {
        alert($(this).find("option:selected").val());
        alert($(this).find("option:selected").text());
    });
});

It is easy to use JS to get the value of a select object


function selectInput(oSelect) {
    alert(oSelect.value);
}

What if I want to use JS to get the text of the select object?


function selectInput(oSelect) {
    alert(oSelect.options[oSelect.selectedIndex].text);
}

If select does not have a default then let the first one be the default, okay?


document.getElementById("test " ).options[0].selected=true;


Related articles: