表单提交上的Javascript / PHP重新填充下拉列表失败

时间:2013-07-02 11:42:13

标签: php javascript html drop-down-menu

我正在使用这样的javascript根据下面的下拉选项加载不同的表单:

<select id = "opts" onchange = "showForm()">
<option value = "0">Select Option</option>
<option value = "1">Option 1</option>
<option value = "2">Option 2</option>
</select>

<div id = "f1" style="display:none">
<form name= "form1">
Content of Form 1
</form>
</div>

<div id = "f2" style="display:none">
<form name= "form2">
Content of Form 2
</form>
</div>

<script type = "text/javascript">
function showForm(){
var selopt = document.getElementById("opts").value;
if (selopt == 1) {
document.getElementById("f1").style.display="block";
document.getElementById("f2").style.display="none";
}
if (selopt == 2) {
document.getElementById("f2").style.display="block";
document.getElementById("f1").style.display="none";
}
}

</script>

我删除了实际的表格细节,因为它们在这一点上并不重要。无论如何,当提交表单时,它会通过一系列验证:

if (isset($_POST['submitted'])) { 
 //validation codes

}

这很有效,但如果验证失败,则会重新加载页面,因此会重置下拉框,并且不会显示先前选择的选项。我希望它保留以前的选择,或者只是在提交失败时将例如加载选择1放入javascript位。任何想法?

伊恩

2 个答案:

答案 0 :(得分:0)

如果验证失败,您可以在javascript的末尾执行此操作

window.onload = function(){
    document.getElementById("opts").value = <?php echo $_POST['opts']; ?>;
}

答案 1 :(得分:0)

使用此

window.onload=function() {
  document.getElementById("opts").onchange=function() {
    var selopt = this.value;
    document.getElementById("f1").style.display=(selopt==1)?"block":"none";
    document.getElementById("f2").style.display=(selopt==2)?"block":"none";
  }
  document.getElementById("opts").onchange(); // show/hide when reloaded
}

使用此PHP将select设置为提交时的任何内容

<? $sel = $_POST['opts']; ?>
<select name="opts" id ="opts">
<option value = "0"<? if ($sel==0) echo " selected ";?>>Select Option</option>
<option value = "1"<? if ($sel==1) echo " selected ";?>>Option 1</option>
<option value = "2"<? if ($sel==2) echo " selected ";?>>Option 2</option>
</select>