-1

I have the dropdown below. I want to populate orange in the dropdown when the page loads. I made a function, PopulateDropDown, which runs the jQuery code to do so, but it is not working.

<select name="cboFruits" id="cboFruits">
    <option value="Apple">Apple</option>
    <option value="Orange">Orange</option>
    <option value="Mango">Mango</option>
    <option value="Banana">Banana</option>
    <option value="Pine">Pine</option>
</select>

<script type="text/javascript" src ="jquery.js"></script>
<script>
    function PopulateDropDown(pFruitName)
    {
        $('cboFruits :selected').val(pFruitName);
    }

    $(document).ready(function(){
        PopulateDropDown('Orange');
    });
</script>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1187
  • 2,116
  • 8
  • 41
  • 74

3 Answers3

1

Well, there are a few problems with your code:

 $('cboFruits :selected').val(pFruitName);

First of all, you're missing the # in front of cboFruits, since cboFruits is the ID property of your select list.

Also the correct way of setting the selected option would be something like this:

function PopulateDropDown(pFruitName)
{
    $('#cboFruits option:contains("'+pFruitName+'")').prop('selected', true);
}

$(document).ready(function(){   
    PopulateDropDown('Orange');
});​

Ref this question How do you select a particular option in a SELECT element in jQuery?

Community
  • 1
  • 1
Yngve B-Nilsen
  • 9,606
  • 2
  • 36
  • 50
0

It should work:

function PopulateDropDown(pFruitName)
{
    $('#cboFruits').val(pFruitName);
}
Mikhail Payson
  • 923
  • 8
  • 12
0

You forgot to write ** # ** and remove selected

$('#cboFruits').val(pFruitName);

EDIT :

or you use

<option value="Orange" selected="true">Orange</option>

when page by default 'Orange' will be selected

mrsrinivas
  • 34,112
  • 13
  • 125
  • 125