Is there a faster way to set the selected value in a dropdown?
I have a dropdown and a picklist. Both contain quite a few of the same items. Basically I am setting the selected dropdown value based on the index of the list item that was clicked.
Code for this:
$('.dropdown-list li').click(function(){
$('#edit-type option').removeAttr('selected', 'selected');
var listvalue = $(this).index();
$('#edit-type option').eq(listvalue).attr('selected', 'selected');
});
It works, but it's rather slow. Delay 3/4 second before selecting the dropdown menu.
Is there a faster way to do this?
EDIT:
<select id="edit-type" name="type" class="form-select" style="display: none; ">
<option value="All">- Any -</option>
<option value="171">item Name 1 </option>
<option value="172" selected="selected">item Name 2</option>
</select>
<ul class="dropdown-list">
<li><div><span>item Name 1</span></div></li>
<li class="selected"><div><span>item Name 2</span></div></li>
</ul>
My reason for this is that I can create a dropdown menu in style.
Thanks Robert
+3
source to share
3 answers
You probably have a lot of items in the list if it's slow. The fastest way is to directly set the selected index:
$('.dropdown-list li').click(function(){
var oDDL = $('#edit-type');
if (oDDL.length > 0)
oDDL[0].selectedIndex = $(this).index();
});
In case you do have a lot of items, it is also much better to use .on()
that will create a single handler behind the scenes instead of a handler for each list item:
$('.dropdown-list').on('click', 'li', function() {
//...
});
+1
source to share