jQuery get value of select onChange

后端 未结 16 1524
星月不相逢
星月不相逢 2020-11-22 05:31

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 sel

相关标签:
16条回答
  • 2020-11-22 05:40
    $('#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>
    
    0 讨论(0)
  • 2020-11-22 05:40

    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
    });
    
    0 讨论(0)
  • 2020-11-22 05:41

    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>

    0 讨论(0)
  • 2020-11-22 05:43

    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.

    0 讨论(0)
  • 2020-11-22 05:45

    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)
        }
    })
    
    0 讨论(0)
  • 2020-11-22 05:48
    jQuery(document).ready(function(){
    
        jQuery("#id").change(function() {
          var value = jQuery(this).children(":selected").attr("value");
         alert(value);
    
        });
    })
    
    0 讨论(0)
提交回复
热议问题