How to post the selections of an HTML List Box with multiple selected values

你离开我真会死。 提交于 2019-12-04 06:38:34

Below you find an example of a page.

Note that:

  • the select element (and any form element) needs a name to be included in the post.
  • only selected options in the select element will be posted.

What values are selected in the box by the user?

When the user submits the form only the selected values will be sent to the server. Depending on what language you are using at the server there are different ways to access them.

What are the options added to the box by the user?

As stated before you only see what options that was selected. But how do you distinguish between your options and the users options? That depends on what data you are sending the user. The universal answer is thats the value you get back that you didn't send. However this can be simplified depending on your data. Since the options have both a value and a text property, one way it to use a numeric value for your pregenerated values. That way your values will be numeric in the reply and the users values will be a text string. This approach assumes that your user will not enter just a numeric value. Another approach is to add a prefix to all user generated values (remember you have both a value and a text field for all options)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Test of select box</title>
    <script type="text/javascript">
      function addOpt(e) {
        var o=document.createElement("option");
        //o.value= -e.options.length;
        o.text = "Test " + e.options.length;
        o.selected=true;
        e.add(o,null);
      }
    </script>
  </head>
  <body>
    <form method="post" action="mypage.html">
      <input type="button" onclick="addOpt(this.form.myselect)" value="Add option"/>
      <br/>
      <select id="myselect" name="mydata" multiple="multiple" size="10">
        <option value="0">Test 0</option>
        <option value="1">Test 1</option>
        <option value="2">Test 2</option>
      </select>
      <br/>
      <input type="submit"/>
    </form>
  </body>
</html>

By naming your select with trailing square brackets, PHP (and likely other server languages) will put the data in an array

ex:

<form action="process.php" method="post">
  <select name="multiSelects[]" multiple="multiple" size="5">
    <option value="0">Zero</option>
    <option value="1">One</option>
  </select>
  <input type="submit" />
</form>

The selections will be available in the array $_POST['multiSelects']

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!