Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing selected option on button click

On click of a button I'm wanting to change the selected option in a select list to correspond to the button that was clicked. This is what I have so far, jsfiddle

$('#btnCityAuckland').click(function(){
    $('#City').val('A');
})

I do have some jQuery there, but its probably miles off being right as it cant be that simple.

like image 377
Jamesil Avatar asked Oct 03 '12 07:10

Jamesil


People also ask

How to get select option value in JavaScript?

To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property. The value "en" will be printed on the console (Ctrl + Shift + J to open the console).


1 Answers

$('#btnAuckland').click(function(){ 
    $('#City').val('A').trigger('change');
})​

Apparently you can just call the .trigger() method after setting the value.

Demo: http://jsfiddle.net/8RUBj/11/

EDIT
Also, it's better if you use data attributes to set the value, and classes, and then you can do all your buttons in one go.

$('.select-change').click(function(){ 
    $('#City').val($(this).data('val')).trigger('change');
})​

Demo v2: http://jsfiddle.net/8RUBj/15/

like image 57
ahren Avatar answered Sep 28 '22 09:09

ahren