[jquery] 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.

This question is related to jquery select

The answer is


For all selects, invoke this function.

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

For only one select:

$('#select_id') 

jQuery get value of select html elements using on Change event

For Demo & More Example

_x000D_
_x000D_
$(document).ready(function () {   _x000D_
    $('body').on('change','#select_box', function() {_x000D_
         $('#show_only').val(this.value);_x000D_
    });_x000D_
}); 
_x000D_
<!DOCTYPE html>  _x000D_
<html>  _x000D_
<title>jQuery Select OnChnage Method</title>_x000D_
<head> _x000D_
 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>    _x000D_
</head>  _x000D_
<body>  _x000D_
<select id="select_box">_x000D_
 <option value="">Select One</option>_x000D_
    <option value="One">One</option>_x000D_
    <option value="Two">Two</option>_x000D_
    <option value="Three">Three</option>_x000D_
    <option value="Four">Four</option>_x000D_
    <option value="Five">Five</option>_x000D_
</select>_x000D_
<br><br>  _x000D_
<input type="text" id="show_only" disabled="">_x000D_
</body>  _x000D_
</html>  
_x000D_
_x000D_
_x000D_


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


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

You can try this (using jQuery)-

_x000D_
_x000D_
$('select').on('change', function()_x000D_
{_x000D_
    alert( this.value );_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>_x000D_
    <option value="3">Option 3</option>_x000D_
    <option value="4">Option 4</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Or you can use simple Javascript like this-

_x000D_
_x000D_
function getNewVal(item)_x000D_
{_x000D_
    alert(item.value);_x000D_
}
_x000D_
<select onchange="getNewVal(this);">_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>_x000D_
    <option value="3">Option 3</option>_x000D_
    <option value="4">Option 4</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


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

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", "Subat", "Mart", "Nisan", "Mayis", "Haziran", "Temmuz", "Agustos", "Eylül", "Ekim", "Kasim", "Aralik"],
                    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();
                    }
                });
            }
        })

    }

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.


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

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

only with JS

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

$('#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>

jQuery(document).ready(function(){

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

    });
})

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

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
}