从php中的下拉菜单创建一个项目列表


Creating a list of items from dropdown menu in php

我一直在尝试实现一个下拉列表,如果进行了选择,它将在下拉列表上方列出所选项目。

我正在使用下面的网站

http://odyniec.net/articles/multiple-select-fields/

我使用的特定部分在"Fancy Javascript Method"下面,但我把代码放在jsfiddle中,它不起作用,如图所示。

有人能帮我吗?感谢您的帮助。

谢谢!

我稍微清理了一下,代码有点偏离

function selectIngredient(select) {
    var value = select.val();
    var $ul = $(select).prev('ul');
  if ($ul.find('input[value=' + value + ']').length == 0)
    $ul.append('<li onclick="$(this).remove();">' +
      '<input type="hidden" name="ingredients[]" value="' + 
      value + '" /> ' + value + '</li>');
}
$('select.options').on('change' , function() {
    selectIngredient($(this)); 
});

演示:http://jsfiddle.net/c5s9c/

试试这个:

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="content-type" content="text/html" />
    <title>Ingredients</title>
    <script type="text/javascript">
    <!--
        function selectIngredient(select)
    {
      var option = select.options[select.selectedIndex];
      var ul = select.parentNode.getElementsByTagName('ul')[0];
      var choices = ul.getElementsByTagName('input');
      for (var i = 0; i < choices.length; i++)
        if (choices[i].value == option.value)
          return;
      var li = document.createElement('li');
      var input = document.createElement('input');
      var text = document.createTextNode(option.firstChild.data);
      input.type = 'hidden';
      input.name = 'ingredients[]';
      input.value = option.value;
      li.appendChild(input);
      li.appendChild(text);
      li.setAttribute('onclick', 'this.parentNode.removeChild(this);');     
      ul.appendChild(li);
    }
    -->
    </script>
</head>
<body>
<?php
if ( isset( $_POST['ingredients'] ) ) {
    if ( !empty( $_POST['ingredients'] ) ) {
        echo '<fieldset><legend>Your ingredients</legend>';
        foreach ( $_POST['ingredients'] as $ingredient ) {
            echo '<p>- ', $ingredient, '</p>';
        }
        echo '</fieldset>';
    } else {
        echo '<p>No ingredients selected!</p>';
    }
}
?>
<form action="" method="post">
<ul>
 <li onclick="this.parentNode.removeChild(this);">
  <input type="hidden" name="ingredients[]" value="Cheese" />
  Cheese
 </li>
 <li onclick="this.parentNode.removeChild(this);">
  <input type="hidden" name="ingredients[]" value="Ham" />
  Ham
 </li>
 <li onclick="this.parentNode.removeChild(this);">
  <input type="hidden" name="ingredients[]" value="Mushrooms" />
  Mushrooms
 </li>
</ul>
<select onchange="selectIngredient(this);">
 <option value="Cheese">Cheese</option>
 <option value="Olives">Olives</option>
 <option value="Pepperoni">Pepperoni</option>
</select>
<input type="submit" value="go" />
</form>
</body>
</html>