ChatGPT解决这个技术问题 Extra ChatGPT

jQuery get value of select onChange

I was under the impression that I could get the value of a select input by doing this $(this).val(); and applying the onchange parameter to the select field.

It would appear it only works if I reference the ID.

How do I do it using this.


m
moffeltje

Try this-

$('select').on('change', function() { alert( this.value ); });

You can also reference with onchange event-

function getval(sel) { alert(sel.value); }


I know this is quite late but if you are using the keyboard (tabbing) to navigate a form and use the up/down arrows to choose from a dropdown list then FireFox (22.0) does not trigger the change event. You need to additionally bind keypress for FireFox. Additional Info: jQuery 1.10.2 using the syntax $('select').on('change', function(){ /* do seomthing */ });
D
Darin Dimitrov

I was under the impression that I could get the value of a select input by doing this $(this).val();

This works if you subscribe unobtrusively (which is the recommended approach):

$('#id_of_field').change(function() {
    // $(this).val() will work here
});

if you use onselect and mix markup with script you need to pass a reference to the current element:

onselect="foo(this);"

and then:

function foo(element) {
    // $(element).val() will give you what you are looking for
}

i
ilgam

This is helped for me.

For select:

$('select_tags').on('change', function() {
    alert( $(this).find(":selected").val() );
});

For radio/checkbox:

$('radio_tags').on('change', function() {
    alert( $(this).find(":checked").val() );
});

D
Daniel

Try the event delegation method, this works in almost all cases.

$(document.body).on('change',"#selectID",function (e) {
   //doStuff
   var optVal= $("#selectID option:selected").val();
});

R
Rakesh Maurya
$('#select_id').on('change', function()
{
    alert(this.value); //or alert($(this).val());
});



<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id="select_id">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
</select>

S
Sharuk Ahmed

Arrow function has a different scope than function, this.value will give undefined for an arrow function. To fix use

$('select').on('change',(event) => {
     alert( event.target.value );
 });

j
jsims281

You can try this (using jQuery)-

$('select').on('change', function() { alert( this.value ); });

Or you can use simple Javascript like this-

function getNewVal(item) { alert(item.value); }


H
Hai Nguyen
$('#select-id').change(function() {
    console.log($(this).val());
});

if somebody also need to get the text of the option, here is it $(this).find('option:selected').text();
T
TRiG

For all selects, invoke this function.

$('select').on('change', function()
{
    alert( this.value );
});

For only one select:

$('#select_id') 

D
Developer

jQuery get value of select html elements using on Change event

For Demo & More Example

$(document).ready(function () { $('body').on('change','#select_box', function() { $('#show_only').val(this.value); }); }); jQuery Select OnChnage Method


d
drjorgepolanco

This is what worked for me. Tried everything else with no luck:

<html>

  <head>
    <title>Example: Change event on a select</title>

    <script type="text/javascript">

      function changeEventHandler(event) {
        alert('You like ' + event.target.value + ' ice cream.');
      }

    </script>

  </head>

  <body>
    <label>Choose an ice cream flavor: </label>
    <select size="1" onchange="changeEventHandler(event);">
      <option>chocolate</option>
      <option>strawberry</option>
      <option>vanilla</option>
    </select>
  </body>

</html>

Taken from Mozilla


h
heena Jethva

Look for jQuery site

HTML:

<form>
  <input class="target" type="text" value="Field 1">
  <select class="target">
    <option value="option1" selected="selected">Option 1</option>
    <option value="option2">Option 2</option>
  </select>
</form>
<div id="other">
  Trigger the handler
</div>

JAVASCRIPT:

$( ".target" ).change(function() {
  alert( "Handler for .change() called." );
});

jQuery's example:

To add a validity test to all text input elements:

$( "input[type='text']" ).change(function() {
  // Check input( $( this ).val() ) for validity here
});

V
Virendra Yaduvanshi
jQuery(document).ready(function(){

    jQuery("#id").change(function() {
      var value = jQuery(this).children(":selected").attr("value");
     alert(value);

    });
})

4
4braincells

Let me share an example which I developed with BS4, thymeleaf and Spring boot.

I am using two SELECTs, where the second ("subtopic") gets filled by an AJAX call based on the selection of the first("topic").

First, the thymeleaf snippet:

 <div class="form-group">
     <label th:for="topicId" th:text="#{label.topic}">Topic</label>
     <select class="custom-select"
             th:id="topicId" th:name="topicId"
             th:field="*{topicId}"
             th:errorclass="is-invalid" required>
         <option value="" selected
                 th:text="#{option.select}">Select
         </option>
         <optgroup th:each="topicGroup : ${topicGroups}"
                   th:label="${topicGroup}">
             <option th:each="topicItem : ${topics}"
                     th:if="${topicGroup == topicItem.grp} "
                     th:value="${{topicItem.baseIdentity.id}}"
                     th:text="${topicItem.name}"
                     th:selected="${{topicItem.baseIdentity.id==topicId}}">
             </option>
         </optgroup>
         <option th:each="topicIter : ${topics}"
                 th:if="${topicIter.grp == ''} "
                 th:value="${{topicIter.baseIdentity.id}}"
                 th:text="${topicIter.name}"
                 th:selected="${{topicIter.baseIdentity?.id==topicId}}">
         </option>
     </select>
     <small id="topicHelp" class="form-text text-muted"
            th:text="#{label.topic.tt}">select</small>
</div><!-- .form-group -->

<div class="form-group">
    <label for="subtopicsId" th:text="#{label.subtopicsId}">subtopics</label>
    <select class="custom-select"
            id="subtopicsId" name="subtopicsId"
            th:field="*{subtopicsId}"
            th:errorclass="is-invalid" multiple="multiple">
        <option value="" disabled
                th:text="#{option.multiple.optional}">Select
        </option>
        <option th:each="subtopicsIter : ${subtopicsList}"
                th:value="${{subtopicsIter.baseIdentity.id}}"
                th:text="${subtopicsIter.name}">
        </option>
    </select>
    <small id="subtopicsHelp" class="form-text text-muted"
           th:unless="${#fields.hasErrors('subtopicsId')}"
           th:text="#{label.subtopics.tt}">select</small>
    <small id="subtopicsIdError" class="invalid-feedback"
           th:if="${#fields.hasErrors('subtopicsId')}"
           th:errors="*{subtopicsId}">Errors</small>
</div><!-- .form-group -->

I am iterating over a list of topics that is stored in the model context, showing all groups with their topics, and after that all topics that do not have a group. BaseIdentity is an @Embedded composite key BTW.

Now, here's the jQuery that handles changes:

$('#topicId').change(function () {
    selectedOption = $(this).val();
    if (selectedOption === "") {
        $('#subtopicsId').prop('disabled', 'disabled').val('');
        $("#subtopicsId option").slice(1).remove(); // keep first
    } else {
        $('#subtopicsId').prop('disabled', false)
        var orig = $(location).attr('origin');
        var url = orig + "/getsubtopics/" + selectedOption;
        $.ajax({
            url: url,
           success: function (response) {
                  var len = response.length;
                    $("#subtopicsId option[value!='']").remove(); // keep first 
                    for (var i = 0; i < len; i++) {
                        var id = response[i]['baseIdentity']['id'];
                        var name = response[i]['name'];
                        $("#subtopicsId").append("<option value='" + id + "'>" + name + "</option>");
                    }
                },
                error: function (e) {
                    console.log("ERROR : ", e);
                }
        });
    }
}).change(); // and call it once defined

The initial call of change() makes sure it will be executed on page re-load or if a value has been preselected by some initialization in the backend.

BTW: I am using "manual" form validation (see "is-valid"/"is-invalid"), because I (and users) didn't like that BS4 marks non-required empty fields as green. But that's byond scope of this Q and if you are interested then I can post it also.


C
Colin D

Note that if these are not working, it might be because the DOM has not loaded and your element was not found yet.

To fix, put the script at the end of body or use document ready

$.ready(function() {
    $("select").on('change', function(ret) {  
         console.log(ret.target.value)
    }
})

H
Henry Lancy Muschett Oliva

only with JS

 let select=document.querySelectorAll('select') 
  select.forEach(function(el) {
    el.onchange =  function(){
     alert(this.value);
      
  }}
  )

a
ahmed

i have an example to help in new ideas. i hope this will help anybody.

$('#editpricelist_box').change(function ($e){
    $('input[name="edit_unit_price"]').val(parseFloat(this.val()).toFixed(2));
    console.log(this.val());
});

E
Eric Aya

I want to add, who needs full custom header functionality

   function addSearchControls(json) {
        $("#tblCalls thead").append($("#tblCalls thead tr:first").clone());
        $("#tblCalls thead tr:eq(1) th").each(function (index) {
            // For text inputs
            if (index != 1 && index != 2) {
                $(this).replaceWith('<th><input type="text" placeholder=" ' + $(this).html() + ' ara"></input></th>');
                var searchControl = $("#tblCalls thead tr:eq(1) th:eq(" + index + ") input");
                searchControl.on("keyup", function () {
                    table.column(index).search(searchControl.val()).draw();
                })
            }
            // For DatePicker inputs
            else if (index == 1) {
                $(this).replaceWith('<th><input type="text" id="datepicker" placeholder="' + $(this).html() + ' ara" class="tblCalls-search-date datepicker" /></th>');

                $('.tblCalls-search-date').on('keyup click change', function () {
                    var i = $(this).attr('id');  // getting column index
                    var v = $(this).val();  // getting search input value
                    table.columns(index).search(v).draw();
                });

                $(".datepicker").datepicker({
                    dateFormat: "dd-mm-yy",
                    altFieldTimeOnly: false,
                    altFormat: "yy-mm-dd",
                    altTimeFormat: "h:m",
                    altField: "#tarih-db",
                    monthNames: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"],
                    dayNamesMin: ["Pa", "Pt", "Sl", "Ça", "Pe", "Cu", "Ct"],
                    firstDay: 1,
                    dateFormat: "yy-mm-dd",
                    showOn: "button",
                    showAnim: 'slideDown',
                    showButtonPanel: true,
                    autoSize: true,
                    buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
                    buttonImageOnly: false,
                    buttonText: "Tarih Seçiniz",
                    closeText: "Temizle"
                });
                $(document).on("click", ".ui-datepicker-close", function () {
                    $('.datepicker').val("");
                    table.columns(5).search("").draw();
                });
            }
            // For DropDown inputs
            else if (index == 2) {
                $(this).replaceWith('<th><select id="filter_comparator" class="styled-select yellow rounded"><option value="select">Seç</option><option value="eq">=</option><option value="gt">&gt;=</option><option value="lt">&lt;=</option><option value="ne">!=</option></select><input type="text" id="filter_value"></th>');

                var selectedOperator;
                $('#filter_comparator').on('change', function () {
                    var i = $(this).attr('id');  // getting column index
                    var v = $(this).val();  // getting search input value
                    selectedOperator = v;
                    if(v=="select")
                        table.columns(index).search('select|0').draw();
                    $('#filter_value').val("");
                });

                $('#filter_value').on('keyup click change', function () {
                    var keycode = (event.keyCode ? event.keyCode : event.which);
                    if (keycode == '13') {
                        var i = $(this).attr('id');  // getting column index
                        var v = $(this).val();  // getting search input value
                        table.columns(index).search(selectedOperator + '|' + v).draw();
                    }
                });
            }
        })

    }