0

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

我正在使用下面的网站

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

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

谁能帮帮我吗?任何帮助表示赞赏。

谢谢!

4

2 回答 2

0

试试这个:

<!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>
于 2013-02-13T15:51:08.143 回答
0

我清理了一下,代码有点不对劲。

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/

于 2013-02-13T15:55:07.317 回答