简体   繁体   English

使用JavaScript将下拉框的值设置为最后提交的值

[英]Setting value of dropdown box to last submitted value with javascript

I have the following dropdown box 我有以下下拉框

<form name="myform" method="POST" ACTION="songs.php">
Select Category: <select id="sel" name="categories" onchange="document.myform.submit()">

And all the options follow after. 并且所有选项都在后面。 When the user makes a selection, the category is brought up below using PHP and MYSQl based on the selection containing a list of songs etc. 当用户进行选择时,基于包含歌曲列表等的选择,使用PHP和MYSQl在下面显示类别。

However, the dropdown box always defaults back to the first value in the list of options. 但是,下拉框始终默认返回到选项列表中的第一个值。 How do I make so that the dropdown box will set the selected option to the last submitted value? 如何使下拉框将所选选项设置为最后提交的值? Thanks in advance! 提前致谢!

You can't do that with JS as it has no direct access to POST request parameters. 您无法使用JS执行此操作,因为它无法直接访问POST请求参数。 Rather let the server side language (which is in your case PHP) print the selected attribute on the <option> element whenever the submitted value matches the option value. 而是让服务器端语言(在您的情况下为PHP)在提交的值与选项值匹配时在<option>元素上打印selected属性。

Eg 例如

foreach ($options as $value => $label) {
    echo '<option value="' . $value . '"' . ($selected == $value ? ' selected' : '') . '>' . $label . '</option>';
}

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

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