I'm trying to use Jquery to change the value from a "select" input in a form, but when it changes, the function for that change doesn't work.
HTML:
<select id='select'>
<option checked value='1' >Option 1</option>
<option value='2' >Option 2</option>
</select>
<div id='text'>Option 1 selected</div>
<div id='button'>Click to select Option 2</div>
JQuery:
$('#select').change(function(){
if($(this).val() == '1'){
$('#text').text('Option 1 selected');
} else if($(this).val() == '2'){
$('#text').text('Option 2 selected');
}
});
$('#button').click(function(){
$('#select').val('2');
})
CSS:
#button {
cursor: pointer;
color: white;
background: red;
padding: 5px;
display: inline-block;
}
Demo: https://jsfiddle.net/fdko9nna/
When I click the #button
div, it changes the select field, but the function that changes the #text
it's not executed.
Thanks.
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.
The change event occurs when the value of an element has been changed (only works on <input>, <textarea> and <select> elements). The change() method triggers the change event, or attaches a function to run when a change event occurs. Note: For select menus, the change event occurs when an option is selected.
jQuery val() Method The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.
You need to trigger the change event with either .change()
or trigger('change')
in your button's code:
$('#button').click(function(){
$('#select').val('2').change();
})
The change event you bound to the select doesn't get triggered by changing the value via jQuery alone, so you need to invoke jQuery's change event.
jsFiddle example
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