0

I have a HTML dropdown list with single selection. I want to select a value according to an value which I get from the database.

<select name="aa">
    <option>BE</option>
    <option>TE</option>
    <option>SE</option>
</select>

I get the value "TE" from the db and then I tried these 3 ways of setting the associated option tag selected.

if($m_aa == "TE"){
$script = <<< EOF
<script type='text/javascript'>
    jQuery(document).ready(function($) {
        // $('#aa option:contains("' + BE + '")').attr('selected', 'selected'); //won't work
        // $('#aa option:eq(0)').attr('selected', 'selected'); //won't work
        $('#aa option:eq(1)').prop('selected', true); //won't work
     });
</script>
EOF;
echo $script;
}
....

<dropdown list>

But none of the 3 possibilities will work. Firebug don't show any error, if I add an alert(); it will shown. So syntactically it should be fine. I use jquery version 1.8.6 within a wordpress plugin in which this functionality I mentioned above should be implemented.

BR, mybecks

2 Answers 2

2

To set the selected option of a <select> you can use the .val() function:

<script type='text/javascript'>
    jQuery(document).ready(function($) {
        $('#aa').val('<?php echo $m_aa; ?>');
     });
</script>

Also, I noticed that you have <select name="aa">, you should add id="aa" as well for the code to work, or change the selector to $('select[name=aa]').

Sign up to request clarification or add additional context in comments.

2 Comments

Actually his only error was trying to select the option by id when it should be by name. So only changing the selector to this $('select[name="aa"] option:eq(1)').prop('selected', true); works very well. Your alternative should work well also.
Thanks for your answers & comments. @Christoffer solution works great for me, using it with dynamic data. :-)
0

try using jquery version 1.7.x

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.