Dreteh
Dreteh

Reputation: 387

Jquery: How to programmatically select an option within a li element

I want to select an option by text. Here is my javascript function. I tried two ways but no luck. Help is appreciated. Thank you.

function preselect(selectedText)
{
     //not ok
     $('#item1 .partDesc').val(selectedText);

     //not ok either
     $('#item1 .partDesc option[value='+ selectedText +']').attr('selected', 'selected');
}

<ul id="myUL">
   <li id="item1">
      <select class="partDesc"><option>Front</option><option>Rear</option></select>
      <input type="text" class="itemDesc">
      <img src="images/myimg.jpg" class="itemImg" > 
   </li>
   <li id="item2">
      <select class="partDesc"><option>Front</option><option>Rear</option></select>
      <input type="text" class="itemDesc">
      <img src="images/myimg.jpg" class="itemImg" > 
   </li>
</ul>

Upvotes: 1

Views: 1131

Answers (2)

profanis
profanis

Reputation: 2751

I hope this helps

$(document).ready(function(){
    $('.itemDesc').keyup(function(){
        var defaultSelection = "Front";
        var element = $(this).parents("li").find('.partDesc');
        element.val($(this).val());
        if(element.val()==null){
            element.val(defaultSelection);
        };
    });
});

Upvotes: 0

Aistina
Aistina

Reputation: 12679

What you're looking for is the :contains() selector.

var myOption = $('#item1 .partDesc option:contains(' + selectedText + ')');

Upvotes: 4

Related Questions