0

In jQuery, if I have an html select with an id of "parentId", how can I select an option where I know the option's value?

Here is the code that I have:

function selectParentId(parentId)
{
    $('#parentId').find('option').each(function(index,element){
     if(element.value == parentId)
        element.prop('selected', true);
     });
}

How do I need to change the above code?

user3736648
  • 7,421
  • 21
  • 73
  • 152
  • Duplicate -> http://stackoverflow.com/questions/13343566/set-select-option-selected-by-value – adeneo Feb 18 '16 at 02:24

2 Answers2

2

To select an item using value you may try this:

$('#parentId option[value="yourvalue"]').prop("selected", 1);

So your function could be re-written as:

function selectDropdown(id, value)
{
    $('#'+id+' option[value="'+value+'"]').prop("selected", 1);
}

So you can call it like:

selectDropdown('theIdOfSelect', 'theValueOfSelect');

An Example Here.

The Alpha
  • 138,380
  • 26
  • 281
  • 300
0

Try this:

function selectParentId(id,value) {
    $('#' + id).val(value)
}
Ibrahim Khan
  • 20,280
  • 7
  • 39
  • 53
Jobelle
  • 2,570
  • 1
  • 14
  • 21