简体   繁体   English

根据会话变量选择下拉值

[英]select dropdown value based on session variable

i have a php form which submits data to another php for validation. 我有一个php表单,可将​​数据提交到另一个php进行验证。 if any fields are left blank the validator php sends a message back to original php form along with all the pre filled variables using session variables so that user doesn't have to fill them again. 如果任何字段留为空白,验证器php会使用会话变量将消息连同所有预填充变量一起发送回原始php表单,从而使用户不必再次填充它们。

i can use these session variables to fill in text boxes again like this 我可以使用这些会话变量再次像这样填写文本框

value="<?php echo $_SESSION['fname'] ?>"

but how to go about populating drop downs, radio buttons and check boxes? 但是如何填充下拉列表,单选按钮和复选框呢?

thanks 谢谢

For a select, checkbox or radio box you would need to check whether the values match. 对于选择,复选框或单选框,您需要检查值是否匹配。 Something like: 就像是:

<select name="fname">
 <option value="1" <?php if($_SESSION['fname'] == 1) echo 'selected'; ?>>1</option>
 <option value="2" <?php if($_SESSION['fname'] == 2) echo 'selected'; ?>>2</option>
</select>

It's easier if you are iterating through the values for the option field: 如果要遍历选项字段的值,则会更容易:

<select name="fname">
 <?php foreach($array AS $key => $value) { ?>
  <option value="<?php echo $value; ?>" <?php if($_SESSION['fname'] == $value) echo 'selected'; ?>><?php echo $value; ?></option>
 <?php } ?>
</select>

A <select> element's selected <option> is not determined by it's value= attribute. <select>元素的选择的<option>不是由其value=属性确定的。 In order to mark an option selected, the <option> element must have the selected attribute set on it, as follows: 为了标记一个选项,必须在<option>元素上设置selected属性,如下所示:

<select>
    <option>1</option>
    <option selected>2</option>
    <option>3</option>
</select>

In order to do this programmatically, you need to iterate through the options, and manually test for the correct option, and add selected to that. 为了以编程方式执行此操作,您需要遍历选项,并手动测试正确的选项,然后将selected添加到该选项中。

There is a far simpler method using JQuery. 有一个使用JQuery的简单得多的方法。 You can set Selects with .val() so make the most of it. 您可以使用.val()设置Selects,以便充分利用它。

<script type="text/javascript">
$("#fname").val("<?php echo $_SESSION['fname']; ?>");
</script>

Don't forget to set the id of the select as well as the name to fname . 不要忘记将select的ID以及名称设置为fname

... Noticed that your double quote at the end of the statement was misplaced, it should be: ...注意,语句末尾的双引号放错了位置,应为:

<script>
    $("#fname").val("<?php echo $_SESSION['fname'] ?>");
</script>

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

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