When you dynamically set a value in a textfield using jQuery . val(), you have to manually trigger the . change event if you want to add extra code that trigger when the value of the field change.
Using the jQuery change() method; you can set the selected value of dropdown in jquery by using id, name, class, and tag with selected html elements; see the following example for that: Example 1 :- Set selected value of dropdown in jquery by id.
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');
To select an option, use .val('value-of-the-option')
on the select element. To trigger the change element, use .change()
or .trigger('change')
.
The problems in your code are the comma instead of the dot in $('.check'),trigger('change');
and the fact that you call it before binding the event handler.
$('#edit_user_details').find('select').trigger('change');
It would change the select html tag drop-down item with id="edit_user_details"
.
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"));
Give links in value of the option tag
<select size="1" name="links" onchange="window.location.href=this.value;">
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
</select>
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With