Reputation: 165
I have this piece of code for select option:
<select class="select-box" name="select-choice-month" id="select-locations">
<option id="1">Select Region</option>
<option id="2" value="eu">Europe</option>
<option id="3" value="nam">North America</option>
<option id="4" value="sam">Latin America</option>
<option id="5" value="aspa">Asia/Pacific</option>
</select>
On select change I already have to change its background like this (displaying or hiding specific div):
$('#select-locations').change(function() {
$('#form1, #form2, #form3, #form4, #form5').hide();
$('#form' + $(this).find('option:selected').attr('id')).show();
});
But, now I have mini navigation which is also displaying or hiding same div's
<div id="map-menu">
<a href="#" id="3">North America</a>
<a href="#" id="4">Latin America</a>
<a href="#" id="5">Asia/Pacific</a>
</div><!-- end of map-menu -->
Jquery for this:
$('#map-menu a').click(function() {
$('#form1, #form2, #form3, #form4, #form5').hide();
$('#form' + $(this).attr('id')).show();
});
How can I achieve when anchor is clicked and div is changed to change output (name) of selected option also? In first example that is working, but when I am changing it through anchors it doesnt work ...
Tnx for any answers
Upvotes: 2
Views: 1935
Reputation: 21553
If I read your question correctly then I think the following should solve your problem and reduce code repetition.
$('#map-menu a').click(function() {
$('#select-locations').val(this.id).change();
});
It will listen for a click on the a
s and then set the value of the select list to the clicked id
. Once this is complete it will trigger the change
event on the select list causing your change
listener to be triggered.
Also a note on your id
s they should not just be a number:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Source: https://stackoverflow.com/a/703790/461813
If you want to use your current HTML then it would be something like this:
$('#map-menu a').click(function() {
var select = $('#select-locations');
var option_to_select = $('option[id="' + this.id + '"]', select);
select.val(option_to_select.val()).change();
});
But it should be noted that your code currently does not have unique id
s so I suggest you namespace them like:
select_option_1
anchor_option_1
Then the above code would become:
$('#map-menu a').click(function() {
var option_id = this.id.replace('anchor', 'select');
var select = $('#select-locations');
var option_to_select = $('option[id="' + option_id + '"]', select);
select.val(option_to_select.val()).change();
});
And here it is as a jsFiddle you can run: http://jsfiddle.net/6tHnj/
Upvotes: 1