복붙노트

[JQUERY] 선택의 onChange의 가치를 jQuery를

JQUERY

선택의 onChange의 가치를 jQuery를

해결법


  1. 1.이 시도-

    이 시도-

    $ ( '선택'). ( '변화', 기능에 대한 () { 경고 (this.value); }); <스크립트 SRC = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> <선택> <옵션 값 = "1"> 한 <옵션 값 = "2"> 두

    또한 onchange를 이벤트 -로 참조 할 수 있습니다

    함수 GETVAL (SEL) { 경고 (sel.value); } <옵션 값 = "1"> 한 <옵션 값 = "2"> 두


  2. 2.당신이 (권장 접근이다) 겸손하게 가입 할 경우에 작동합니다 :

    당신이 (권장 접근이다) 겸손하게 가입 할 경우에 작동합니다 :

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

    당신이 onSelect를 사용하여 스크립트를 마크 업 믹스 현재 요소에 대한 참조를 전달해야하는 경우 :

    onselect="foo(this);"
    

    그리고:

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

  3. 3.이것은 나를 위해 도움이됩니다.

    이것은 나를 위해 도움이됩니다.

    선택의 경우 :

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

    라디오 / 체크 박스의 경우 :

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

  4. 4.이벤트 위임 방법, 거의 모든 경우에서이 작품을보십시오.

    이벤트 위임 방법, 거의 모든 경우에서이 작품을보십시오.

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

  5. 5.화살표 기능, 기능과 다른 범위가 this.value을 화살표 함수 미정 줄 것이다. 수정 사용하기

    화살표 기능, 기능과 다른 범위가 this.value을 화살표 함수 미정 줄 것이다. 수정 사용하기

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

  6. 6.이 (사용하여 jQuery를) 시도 할 수 있습니다 -

    이 (사용하여 jQuery를) 시도 할 수 있습니다 -

    $ ( '선택'). ( '변화', 기능에 대한 () { 경고 (this.value); }); <스크립트 SRC = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> <선택> <옵션 값 = "1"> 옵션 1 <옵션 값 = "2"> 옵션 2 <옵션 값 = "3"> 옵션 3 <옵션 값 = "4"> 옵션 4

    또는 당신은 this- 같은 간단한 자바 스크립트를 사용할 수 있습니다

    함수 getNewVal (항목) { 경고 (item.value); } <옵션 값 = "1"> 옵션 1 <옵션 값 = "2"> 옵션 2 <옵션 값 = "3"> 옵션 3 <옵션 값 = "4"> 옵션 4


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

  8. 8.이것은 나를 위해 일한 것입니다. 행운과 다른 시도 모든 :

    이것은 나를 위해 일한 것입니다. 행운과 다른 시도 모든 :

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

    모질라에서 촬영


  9. 9.jQuery를 사이트 봐

    jQuery를 사이트 봐

    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의 예 :

    모든 텍스트 입력 요소에 유효성 검사를 추가하려면 :

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

  10. 10.모든 선택은이 함수를 호출한다.

    모든 선택은이 함수를 호출한다.

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

    단 하나의 선택 :

    $('#select_id') 
    

  11. 11.변경 이벤트에 사용하는 HTML을 선택 요소의 가치를 jQuery를

    변경 이벤트에 사용하는 HTML을 선택 요소의 가치를 jQuery를

    데모 및 추가 예를 들어

    $ (문서) .ready (함수 () { $ ( '신체'). ( '변경', '#의 select_box'기능에 () { $ ( '# show_only') 발 (this.value).; }); }); <제목> jQuery를 선택 OnChnage 방법 <스크립트 SRC = "https://code.jquery.com/jquery-3.3.1.min.js">


  12. 12.이러한 작동하지 않는 경우 DOM이로드되지 않았으며 귀하의 요소가 아직 발견되지 않았기 때문에, 그것은 될 수 있습니다.

    이러한 작동하지 않는 경우 DOM이로드되지 않았으며 귀하의 요소가 아직 발견되지 않았기 때문에, 그것은 될 수 있습니다.

    해결하려면, 신체 또는 사용 문서 준비를 마지막에 스크립트를 넣어

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

  13. 13.

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

  14. 14.제가 BS4, thymeleaf 봄 부팅 개발 예를 공유 할 수 있습니다.

    제가 BS4, thymeleaf 봄 부팅 개발 예를 공유 할 수 있습니다.

    나는 두 번째 ( "하위 항목은") 첫 번째 ( "항목")의 선택을 기반으로 AJAX 호출에 의해 채워집니다 두 건의 SELECT를 사용하고 있습니다.

    첫째, thymeleaf 조각 :

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

    나는 그들의 주제로 모든 그룹을 보여주는 모델 컨텍스트에 저장되는 항목의 목록을 통해 반복하고 있어요 이후 그룹이없는 모든 항목이. BaseIdentity은 BTW @Embedded 복합 키이다.

    자, 여기 핸들 변경 그 jQuery를이다 :

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

    변화의 초기 ()를 호출해야합니다 그것은 페이지를 다시로드에서 실행됩니다하게하거나 값은 백엔드에서 일부 초기화에 의해 미리 선택되어있는 경우.

    BTW : 나는 "수동"양식 유효성 검사를 사용하고 I (사용자가) 그 BS4 마크처럼하지 않았기 때문에 녹색으로 빈 필드를 필수가 아닌, (참조 / "입니다-무효" "-유효"). 그러나의이 Q의 범위은 성공적 당신이 관심이 있다면 다음 나는 또한 그것을 게시 할 수 있습니다.


  15. 15.내가 추가 할, 사람은 전체 사용자 정의 헤더 기능을 필요로

    내가 추가 할, 사람은 전체 사용자 정의 헤더 기능을 필요로

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

  16. 16.JS와 만

    JS와 만

     let select=document.querySelectorAll('select') 
      select.forEach(function(el) {
        el.onchange =  function(){
         alert(this.value);
          
      }}
      )
    
  17. from https://stackoverflow.com/questions/11179406/jquery-get-value-of-select-onchange by cc-by-sa and MIT license