繁体   English   中英

更新选择值(如果数据库中存在)

[英]Update select value if exists in database

我有一个问题,它不会更新2 selects的值。 该值为数字代码,字符串存储在DB中。

这是我的HTML示例:

<select id="jform_country" name="jform[country]" class="form-control required chzn-done">
    <option value="">Select country...</option>
    <option value="1012234" selected="selected">Name country 1</option>
    <option value="1012257">Name country 2</option>
</select>
<select id="jform_city" name="jform[city]" class="form-control required chzn-done">
    <option value="">Select city...</option>
    <option value="1982727" selected="selected">Name city 1</option>
    <option value="1982739">Name city 2</option>
</select>

我用php(getData)中的函数检索数据库值。 但这是我的问题...我试图将变量从PHP传递到JavaScript,它似乎可以正常工作,并且我使用jQuery更改了select的值。 但是,刷新页面时,在某些情况下无法正常工作。

这是我在PHP和jQuery中的代码:

$data = $model->getData();
$country = $data->country;
$city = $data->city;
echo '<script>';
echo 'var selectcountry = '. json_encode($country) .';';
echo 'var selectcity = '. json_encode($city) .';';
echo '</script>';

使用jQuery,我可以接收这些变量:

jQuery(document).ready(function () {

        setTimeout(function() {
            rescueValue(selectcountry, selectcity);
        }, 800);

        function rescueValue(selectcountry, selectcity) {

            if (selectcountry != null) {
                jQuery("#jform_country option:contains('"+ selectcountry +"')").attr("selected", "selected");
                jQuery("#jform_country").trigger("liszt:updated");
            }

            if (selectcity != null) {
                jQuery("#jform_city option:contains('"+ selectcity +"')").attr("selected", "selected");
                jQuery("#jform_city").trigger("liszt:updated");
            }
        }

    });

可能是异步工作吗? 我尝试放置setTimeout但仍然无法解决。 如何使其以简单的方式(类似于此值)恢复PHP值并更新它? 谢谢!

设置select的值比从列表中找到将其设置为selected属性的选项值更正确,例如,如果已经有另一个带有selected属性的选项,可能并不总是有效。

您可以使用jquery.val直接设置值。

jQuery(document).ready(function () {

        setTimeout(function() {
            rescueValue(selectcountry, selectcity);
        }, 800);

        function rescueValue(selectcountry, selectcity) {

            if (selectcountry != null) {
                jQuery("#jform_country").val(selectcountry).trigger("liszt:updated");
            }

            if (selectcity != null) {
                jQuery("#jform_city").val(selectcity).trigger("liszt:updated");
            }
        }

    });

暂无
暂无

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

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