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?

Simon
  • 7,991
  • 21
  • 83
  • 163
  • 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
  • 143,660
  • 29
  • 287
  • 307
0

Try this:

function selectParentId(id,value) {
    $('#' + id).val(value)
}
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
Jobelle
  • 2,717
  • 1
  • 15
  • 26