Change the selected option when the button is pressed

When I click a button, I want to change the selected option in the selection list to match the button I clicked. This is what I still have, jsfiddle

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

I have some jQuery, but its probably miles, being right, as it cannot be so simple.

+6
source share
3 answers
 $('#btnAuckland').click(function(){ $('#City').val('A').trigger('change'); })​ 

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

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

EDIT
It's also better if you use data attributes to set values ​​and classes, and then you can do all of your buttons in one go.

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

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

+14
source

Your code is right, you are simply mistaken $('#btnCityAuckland') , it really is:

 $('#btnAuckland') 

Job demonstration

You can also automate the selection of options based on the button pressed, rather than hard-coded identifiers, for example:

 $('div > a').click(function(){ //click handler for all city buttons $("#City option:contains('"+$(this).text()+"')").attr("selected",true); $("#City").selectmenu('refresh', true); //Refresh to show name on select })​ 

Job demonstration

+3
source

If you are not using jQuery Mobile, your code will work as it is. With jQuery Mobile, you can update the pseudo- .selectmenu("refresh") calling .selectmenu("refresh") on it like this:

 $('div[data-role="controlgroup"] a').click(function(){ $('#City').val( $(this).text().charAt(0) ).selectmenu("refresh"); }); 

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

Note that you do not need to assign a separate click handler for each button: for demo purposes, I showed a rather awkward way to make the code more general so that it works without changing your html, but you could add data- or something attributes to the buttons to indicate which value is associated with each.

Learn more about jQuery Mobile selection methods .

+1
source

Source: https://habr.com/ru/post/926816/


All Articles