简体   繁体   English

根据db中的值选择jquery中的下拉值

[英]Select dropdown value in jquery based on value from db

I have a HTML dropdown list with single selection. 我有一个单选的HTML下拉列表。 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. 我从数据库中获取值“TE”,然后我尝试了这三种设置相关选项标签的方法。

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(); 如果我添加一个alert(),Firebug不会显示任何错误; 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. 我在wordpress插件中使用jquery版本1.8.6,其中我应该实现上面提到的这个功能。

BR, mybecks BR,mybecks

To set the selected option of a <select> you can use the .val() function: 要设置<select>的选定选项,可以使用.val()函数:

<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]') . 另外,我注意到你有<select name="aa"> ,你应该添加id="aa"以使代码工作,或者将选择器更改为$('select[name=aa]')

尝试使用jquery版本1.7.x.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM