I'm trying to trigger a click on a specific option on page load with Select2. I'm getting a URL parameter eg car and I need to click on the option in the select2 with the value of "car"
let params = new URLSearchParams(url.search);
let sourceid = params.get('dynamiccontent');
if(sourceid == 'car'){
alert('yes');
}
This code above works so far because it's alerting.
I need to trigger that click in the if statement. I've tried using
setTimeout(function() {
$('.mySelect option[value="car"]').trigger('click');
$("select.select2-hidden-accessible option[value='sustainability']").trigger('click');
$('.mySelect').val('car').trigger('click');
alert('clicked');
}, 1500)
Use the change event on your select element instead of clicking the option.
$('select.mySelect').select2(); $('select.mySelect').on('change', function() { console.log('run ajax'); }); window.setTimeout(function() { $('select.mySelect').val('car').trigger('change'); }, 1500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <select class="mySelect" style="width: 100px;"> <option value="foo">Foo</option> <option value="car">Car</option> <option value="bar">Bar</option> </select>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.