Trigger change event <select> using jquery

前端 未结 8 1049
别那么骄傲
别那么骄傲 2020-11-28 04:27

is there anyway i could trigger a change event on select box on page load and select a particular option.

Also the function executed by adding the trigger after bin

相关标签:
8条回答
  • 2020-11-28 04:43

    Based on Mohamed23gharbi's answer:

    function change(selector, value) {
        var sortBySelect = document.querySelector(selector);
        sortBySelect.value = value;
        sortBySelect.dispatchEvent(new Event("change"));
    }
    
    function click(selector) {
        var sortBySelect = document.querySelector(selector);
        sortBySelect.dispatchEvent(new Event("click"));
    }
    
    function test() {
        change("select#MySelect", 19);
        click("button#MyButton");
        click("a#MyLink");
    }
    

    In my case, where the elements were created by vue, this is the only way that works.

    0 讨论(0)
  • 2020-11-28 04:45

    If you want to do some checks then use this way

     <select size="1" name="links" onchange="functionToTriggerClick(this.value)">
        <option value="">Select a Search Engine</option>        
        <option value="http://www.google.com">Google</option>
        <option value="http://www.yahoo.com">Yahoo</option>
    </select>
    
    <script>
    
       function functionToTriggerClick(link) {
    
         if(link != ''){
            window.location.href=link;
            }
        }  
    
    </script>
    
    0 讨论(0)
  • 2020-11-28 04:45

    You can try below code to solve your problem:

    By default, first option select: jQuery('.select').find('option')[0].selected=true;

    Thanks, Ketan T

    0 讨论(0)
  • 2020-11-28 04:48

    Another working solution for those who were blocked with jQuery trigger handler, that dosent fire on native events will be like below (100% working) :

    var sortBySelect = document.querySelector("select.your-class"); 
    sortBySelect.value = "new value"; 
    sortBySelect.dispatchEvent(new Event("change"));
    
    0 讨论(0)
  • 2020-11-28 04:52

    Use val() to change to the value (not the text) and trigger() to manually fire the event.

    The change event handler must be declared before the trigger.

    Here's a sample

    $('.check').change(function(){
      var data= $(this).val();
      alert(data);            
    });
    
    $('.check')
        .val('two')
        .trigger('change');
    
    0 讨论(0)
  • 2020-11-28 04:53
    $('#edit_user_details').find('select').trigger('change');
    

    It would change the select html tag drop-down item with id="edit_user_details".

    0 讨论(0)
提交回复
热议问题