开发者

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.

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开发者_JAVA技巧 in advance!


You can't do that with JS as it has no direct access to POST request parameters. 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.

E.g.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜