jQuery krijgt waarde van select onChange

Ik had de indruk dat ik de waarde van een geselecteerde invoer kon krijgen door deze $(this).val();te doen en de parameter onchangetoe te passen op het selectieveld.

Het lijkt erop dat het alleen werkt als ik naar de ID verwijs.

Hoe kan ik dit gebruiken.


Antwoord 1, autoriteit 100%

Probeer dit-

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

Antwoord 2, autoriteit 7%

Ik had de indruk dat ik de waarde van een select kon krijgen
invoer door dit te doen $(this).val();

Dit werkt als u zich onopvallend abonneert (wat de aanbevolen aanpak is):

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

als je onselectgebruikt en opmaak combineert met script, moet je een verwijzing naar het huidige element doorgeven:

onselect="foo(this);"

en dan:

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

Antwoord 3, autoriteit 7%

Dit is geholpen voor mij.

Voor selecteren:

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

Voor radio/selectievakje:

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

Antwoord 4

Probeer de gebeurtenis delegatie methode, dit werkt in bijna alle gevallen.

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

Antwoord 5

Pijlfunctie heeft een ander bereik dan functie,
this.valuegeeft undefined voor een pijlfunctie.
Gebruik

. om het probleem op te lossen

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

Antwoord 6

U kunt dit proberen (met behulp van 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>

Antwoord 7

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

Antwoord 8

Dit is wat voor mij werkte. Al het andere geprobeerd zonder geluk:

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

Overgenomen van Mozilla


Antwoord 9

Zoek naar 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." );
});

voorbeeld van jQuery:

Een validiteitstest toevoegen aan alle tekstinvoerelementen:

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

Antwoord 10

Voor alle selecties, gebruik deze functie.

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

Voor slechts één keuze:

$('#select_id') 

Antwoord 11

jQuery haalt de waarde op van geselecteerde html-elementen met behulp van een wijzigingsgebeurtenis

Voor demo & Meer voorbeeld

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

Antwoord 12

Houd er rekening mee dat als deze niet werken, het kan zijn dat de DOM niet is geladen en uw element nog niet is gevonden.

Om het op te lossen, plaatst u het script aan het einde van de hoofdtekst of gebruikt u document gereed

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

Antwoord 13

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

Antwoord 14

Ik wil toevoegen,
die volledige functionaliteit voor aangepaste kopteksten nodig heeft

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

Antwoord 15

Laat me een voorbeeld delen dat ik heb ontwikkeld met BS4, thymeleaf en Spring boot.

Ik gebruik twee SELECT’s, waarbij de tweede (“subonderwerp”) wordt gevuld door een AJAX-aanroep op basis van de selectie van de eerste (“onderwerp”).

Eerst het tijmbladfragment:

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

Ik herhaal een lijst met onderwerpen die is opgeslagen in de modelcontext, waarbij ik alle groepen met hun onderwerpen laat zien, en daarna alle onderwerpen die geen groep hebben.
BaseIdentity is een @Embedded samengestelde sleutel BTW.

Hier is de jQuery die wijzigingen verwerkt:

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

De initiële aanroep van change() zorgt ervoor dat deze wordt uitgevoerd wanneer de pagina opnieuw wordt geladen of als een waarde vooraf is geselecteerd door een initialisatie in de backend.

BTW: ik gebruik “handmatige” formuliervalidatie (zie “is-valid”/”is-invalid”), omdat ik (en gebruikers) het niet leuk vond dat BS4 niet-vereiste lege velden groen markeert. Maar dat valt buiten het bestek van deze Q en als je geïnteresseerd bent, kan ik het ook posten.


Antwoord 16

alleen met JS

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

Antwoord 17

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

Other episodes