Trying to make a chrome-extension to automate a little daily-chore at my job. So this site has a standard dropDown input something like this below.
<select id="branchList">
<option value="3">KATHMANDU</option>
<option value="18">DELHI</option>
<option value="24">BEIJING</option>
</select>
When I manually click on one of the options it triggers an ajax call and loads the portion of the page with new data. But if I programmatically try to select the option it does not trigger the ajax call. Below is the code I use to select an option which selects the option but does not trigger the ajax call as expected.
document.querySelector("#branchList").value = "18"
I also tried the code below to programmatically click on the element but it still does not trigger the ajax call.
document.querySelector("#branchList").options[1]
Bottom-line is - I'm looking for a way to trigger an ajax call when I select an option from the dropdown with JavaScript.
EDIT - using dispatchEvent
as suggested in the comment.
var elem = document.querySelector("#branchList").options[1]
let event = new Event("click");
elem.dispatchEvent(event);
you need to trigger the change event.
var select = document.getElementById('branchList') select.addEventListener('change', () => { console.log('change') //here should be the ajax call }) function changeSelectValue(num){ select.value = num select.dispatchEvent(new Event('change')); } changeSelectValue(18)
<select id="branchList"> <option value="3">KATHMANDU</option> <option value="18">DELHI</option> <option value="24">BEIJING</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.