Given a <select>
with a few options and given a <span>
for each <option>
, with id = select’s content.
I would like to click on a <span>
and select via jquery the corresponding <option>
(and highlight clicked <span>
);
but I would also like to be able to do the opposite: selecting an option and highlighting the corresponding span.
I created this script. It perfectly if I do one thing or the other. When I try mix click and select it stops working correctly.
function dropdownChangeSelection() {
var id = $('#myselect option:selected').text();
$('#myselect option').removeAttr('selected');
$('#myselect option:contains(' + id + ')').attr('selected', true);
$('.test span').removeClass('bold');
$('#' + id).addClass('bold');
}
function clickChangeSelection() {
var thisid = $(this).attr('id');
$('#myselect option').removeAttr('selected');
$('#myselect option:contains(' + thisid + ')').attr('selected', true);
$('.test span').removeClass('bold');
$('#' + thisid).addClass('bold');
}
$(document).ready(function() {
dropdownChangeSelection();
$('.test span').click(clickChangeSelection);
$('#myselect').click(dropdownChangeSelection);
});
.bold { font-weight: bold; border: 1px solid blue; }
.test span:hover {cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myselect">
<option value="1">US1230213111</option>
<option value="2">US123111903</option>
<option value="3">US1230293200</option>
<option value="4">US1231325565</option>
</select>
<br><br>
<div class="test">
<span id="US1230213111">US1230213111</span>
<br><br>
<span id="US123111903">US123111903</span>
<br><br>
<span id="US1230293200">US1230293200</span>
<br><br>
<span id="US1231325565">US1231325565</span>
</div>
<div class="inner">
</div>
3
Answers
I worked on answers and I worked out my own solution which takes into account option content instead of its value attribute.
the way to do that in simple JS
You can track the changes in your
select
input byonchange
attribute and define a functions to do the action you desire.