Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Select value with Jquery

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 #buttondiv, it changes the select field, but the function that changes the #text it's not executed.
Thanks.

like image 760
Dédi Avatar asked Aug 16 '17 20:08

Dédi


People also ask

How can I change the selected value of a Dropdownlist using jQuery?

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.

How do I use Onchange in jQuery?

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.

How do I set the value of a element in jQuery?

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.


1 Answers

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

like image 148
j08691 Avatar answered Sep 24 '22 23:09

j08691