8

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.

3 Answers 3

13

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

Sign up to request clarification or add additional context in comments.

Comments

1

Based on https://api.jquery.com/change/

Description: Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

This method is a shortcut for .on( "change", handler ) in the first two variations, and .trigger( "change" ) in the third.

The change event is sent to an element when its value changes. This event is limited to elements, boxes and elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

Your value changed in JQuery did not fire the change event, you need to add trigger for the change event.

1 Comment

Explains why the change handler wasn't called, but how could OP ensure that it is in this scenario?
1

Try this:

 $('#button').click(function(){ $('#select option[value="2"]').prop('selected', true); }) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.