amol singh
amol singh

Reputation: 143

fill value and text in select box with jquery

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

but the issue is that , i dosent work when there is value attribute in the <option> tag . I want to to change both the text and value in the select box with the click of a button

code :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 <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 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>GCS</option>
</select>

jquery :

$(function () {
  $('.apps li').click(function () {
    $('.xyz').val($(this).text());
  });
});

fiddle link --> https://jsfiddle.net/2jqfpjLk/1/

this is final working fiddle

https://jsfiddle.net/aoxrLyet/3/

Upvotes: 0

Views: 896

Answers (1)

Milind Anantwar
Milind Anantwar

Reputation: 82241

You need to set option by text as li text is text of option and not its value:

$('.apps li').click(function () {
    litext = $(this).text();
    $('.xyz option').filter(function () { 
              return $(this).html() == litext;
    }).attr('selected', true);
});

Working Demo

Upvotes: 6

Related Questions