jQuery get value of select onChange

JquerySelect

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

Try this-

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

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

<select>
    <option value="1">One</option>
    <option value="2">Two</option>
</select>

You can also reference with onchange event-

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

<select onchange="getval(this);">
    <option value="1">One</option>
    <option value="2">Two</option>
</select>

Solution 2 - Jquery

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

Solution 3 - Jquery

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

Solution 4 - Jquery

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

Solution 5 - Jquery

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

Solution 6 - Jquery

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

Solution 7 - Jquery

You can try this (using jQuery)-

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

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

<select>
    <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>

Or you can use simple Javascript like this-

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

<select onchange="getNewVal(this);">
    <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>

Solution 8 - Jquery

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

Solution 9 - Jquery

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

<!DOCTYPE html>  
<html>  
<title>jQuery Select OnChnage Method</title>
<head> 
 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>    
</head>  
<body>  
<select id="select_box">
 <option value="">Select One</option>
    <option value="One">One</option>
    <option value="Two">Two</option>
    <option value="Three">Three</option>
    <option value="Four">Four</option>
    <option value="Five">Five</option>
</select>
<br><br>  
<input type="text" id="show_only" disabled="">
</body>  
</html>  

Solution 10 - Jquery

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

Solution 11 - Jquery

For all selects, invoke this function.

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

For only one select:

$('#select_id') 

Solution 12 - Jquery

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

Solution 13 - Jquery

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

	});
})

Solution 14 - Jquery

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.

Solution 15 - Jquery

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

Solution 16 - Jquery

only with JS

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

Solution 17 - Jquery

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

    }

Solution 18 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRIKView Question on Stackoverflow
Solution 1 - JquerythecodeparadoxView Answer on Stackoverflow
Solution 2 - JqueryDarin DimitrovView Answer on Stackoverflow
Solution 3 - JqueryilgamView Answer on Stackoverflow
Solution 4 - JqueryKrishnaView Answer on Stackoverflow
Solution 5 - JqueryAnkit PiseView Answer on Stackoverflow
Solution 6 - JquerySharuk AhmedView Answer on Stackoverflow
Solution 7 - JqueryAbrar JahinView Answer on Stackoverflow
Solution 8 - JqueryHai NguyenView Answer on Stackoverflow
Solution 9 - JqueryDeveloperView Answer on Stackoverflow
Solution 10 - JquerydrjorgepolancoView Answer on Stackoverflow
Solution 11 - JqueryAli AsadView Answer on Stackoverflow
Solution 12 - JqueryAndre MesquitaView Answer on Stackoverflow
Solution 13 - JqueryVirendra YaduvanshiView Answer on Stackoverflow
Solution 14 - Jquery4braincellsView Answer on Stackoverflow
Solution 15 - JqueryColin DView Answer on Stackoverflow
Solution 16 - JqueryHenry Lancy Muschett OlivaView Answer on Stackoverflow
Solution 17 - JqueryHamit YILDIRIMView Answer on Stackoverflow
Solution 18 - JqueryahmedView Answer on Stackoverflow