如何防止选择值重置表单提交?

时间:2017-03-29 13:18:37

标签: javascript php

在视图中,

<select id="gender" ng-model="gender">
     <option value=''>Gender?</option>
     <option value="female" >Female</option>
     <option value="male" >Male</option>
     <option value="other" >Other</option>
</select>
<input type="hidden" name="gender" value="{{gender}}">

在提交错误时,将重新提交提交的值并将其作为选择值

var theValue = "<?php echo set_value('gender');?>";
var e = document.getElementById("gender");
e.value = theValue;

在提交不完整的表单时,select应保留post值,并暂时保留,但会再次重置。如何阻止select重置并保留值?

2 个答案:

答案 0 :(得分:0)

试试这个,创建这个PHP函数,

    function __selectedDb($ctrlValue,$dbValue)
{
    if($ctrlValue == $dbValue)
        return "selected='selected'";
    else
        return "";
}

并像这样使用,

<select class="custom-select" id="selImgTiling" name="selImgTiling" value="<?php echo $arrBgSettings['bg_image_tiling']?>">
                                <option value="no-repeat"   <?php echo __selectedDb('no-repeat',$arrBgSettings['bg_image_tiling'])?>>Tiling Off</option>
                                <option value="repeat"      <?php echo __selectedDb('repeat',$arrBgSettings['bg_image_tiling'])?>> Repeat</option>
                                <option value="repeat-x"    <?php echo __selectedDb('repeat-x',$arrBgSettings['bg_image_tiling'])?>>Repeat Horizontal</option>
                                <option value="repeat-y"    <?php echo __selectedDb('repeat-y',$arrBgSettings['bg_image_tiling'])?>>Repeat Vertical</option>
                            </select>

答案 1 :(得分:0)

首先,尝试始终在ng-model指令上使用对象,例如:

ng-model="form.gender"

这里最好描述: If you are not using a .(dot) in your AngularJS models you are doing it wrong?

在响应中,您需要做的就是设置form.gender属性,AngularJS的双向绑定将负责其余的工作。

尝试使用ng-init指令从PHP获取值并在AngularJS控制器上使用它们,如:

ng-init="initGender('<?php echo set_value('gender'); ?>')"

然后在你的AngularJS控制器中:

$scope.form = {};
$scope.initGender = function(gender) {
    $scope.form.gender = gender;
};