Reputation: 143
i have a requirement in which when i click on a element of a list , the element gets shown as a selected option in the select box
i need to use native select box only , not to mention the elements in the list are present in the select dropdown
<button class="quick">QuickLink</button>
<div class="list">
<ul class="apps">
<li>CAPM</li>
<li>GCS</li>
<li>GRS</li>
</ul>
</div>
<select class="xyz">
<option>CAPM</option>
<option>GRS</option>
<option>BDS</option>
<option>CCAS</option>
<option>WEDAT</option>
<option>SDP</option>
</select>
jsfiddle link --> https://jsfiddle.net/8s31w4t9/
Upvotes: 0
Views: 105
Reputation: 12588
You could use data attributes to make your code flexible. And what if you want your li
to have different text to the contents of the option
element?
<ul data-select-target=".xyz">
<li data-select-val="1">CAPM</li>
<li data-select-val="2">GRS</li>
<li data-select-val="3">BDS</li>
</ul>
<select class="xyz">
<option value="1">CAPM</option>
<option value="2">GRS</option>
<option value="3">BDS</option>
<option value="4">CCAS</option>
<option value="5">WEDAT</option>
<option value="6">SDP</option>
</select>
jQuery:
$('[data-select-target] li').click(function(){
var val = $(this).data('select-val');
var target = $(this).closest('ul').data('select-target');
$(target).val(val);
});
Demo: JSFiddle
Upvotes: 0
Reputation: 133403
Bind the click
event with li
and use these methods:
Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
Set the value of each element in the set of matched elements.
Code
$('.apps li').click(function () {
//Get the text of clicked element
var text = $(this).text();
//Set the value of select
$('.xyz').val(text);
});
Upvotes: 4
Reputation: 204
$('.apps').on('click', 'li', function () {
$('.xyz').val(this.innerHTML);
});
Upvotes: 0
Reputation: 769
Use the following solution:
$(function(){
$('.apps li').css("cursor","pointer")
$('.apps li').click(function () {
$('.xyz').val($(this).text());
});
});
Upvotes: -1
Reputation: 193
This should do the work:
$(function(){
$('.apps > li').click(function() {
$('.xyz').val(this.innerHTML);
});
});
Upvotes: 0
Reputation: 15213
Firstly, you want the click
handler to be on your li
s, not your ul
. And secondly, you better use the val
function and specify the text you have in the list to be the val
of the select
:
$('.apps li').click(function(){
$('.xyz').val($(this).text());
});
Upvotes: 1
Reputation: 24276
Check this out:
$(function(){
$('.apps li').click(function(){
$clicked = $(this);
$('.xyz option').each(function(){
if ($(this).text() == $clicked.text()) {
$(this).prop('selected', true);
}
});
});
});
Upvotes: 0