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.
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).
$('#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/
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