我的代码是:
<form method="post">
<select name="item" multiple>
<option value="1">Lotus</option>
<option value="2">Sun Flower</option>
<option value="3">MNC</option>
<option value="4">DELL</option>
<option value="5">LENOVO</option>
</select>
<button type="submit" name="ss">SUBMIT</button>
</form>
<div class="mutiple">
</div>
我想从选项列表中选择多个“不想取值”的项目,然后打印到名为div
的班级multiple
。
例如,如果我选择 Lotus和Sun Flower ,那么我想打印 Lotus和Sun Flower,而不仅仅是它的值。
答案 0 :(得分:1)
如果您想使用JavaScript,可以参考以下代码:
<form method="post">
<select name="item[]" multiple>
<option value="1">Lotus</option>
<option value="2">Sun Flower</option>
<option value="3">MNC</option>
<option value="4">DELL</option>
<option value="5">LENOVO</option>
</select>
<button type="submit" name="ss">SUBMIT</button>
</form>
<div class="multiple"></div>
<script>
$('select[name=item]').on('change', function() {
var ul = $('<ul>');
$('.multiple').empty();
$(this).find('option').each(function(index, element) {
if($(element).is(':selected')) {
ul.append('<li>' + $(element).text() + '</li>');
}
});
$('.multiple').html(ul);
});
</script>
或者如果你想用PHP制作它,代码是:
if(!empty($_POST)) {
$products = array(
'1' => 'Lotus',
'2' => 'Sun Flower',
'3' => 'MNC',
'4' => 'DELL',
'5' => 'LENOVO'
);
echo "<ul>";
foreach($_POST['item'] as $item) {
echo "<li>{$products[$item]}</li>";
}
echo "</ul>";
}
答案 1 :(得分:0)
您需要在名称中添加括号:
<select name="item[]" multiple>
然后在服务器端item
将是一个数组:
var_dump($_POST['item']);
您可以将文字作为您选择的值:
<select name="item[]" multiple>
<option value="Lotus">Lotus</option>
<option value="Sun Flower">Sun Flower</option>
<option value="MNC">MNC</option>
<option value="DELL">DELL</option>
<option value="LENOVO">LENOVO</option>
</select>
如果您不想更改值,则应使用DB或数组映射它们:
$pcs = [
"1"=>"Lotus",
"2"=>"Sun Flower",
"3"=>"MNC",
"4"=>"DELL",
"5"=>"LENOVO"
];
foreach($_POST['item'] as $key){
echo $pcs[$key];
}
答案 2 :(得分:0)
很容易:D
<script>
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
var return_div = result;
document.getElementById("selections").innerHTML = return_div;
}
</script>
<select multiple>
<option value="1">Lotus
<option value="2">Sun Flower
<option value="3">MNC
<option value="4">DELL
<option value="5">LENOVO
</select>
<button onclick="var el = document.getElementsByTagName('select')[0]; getSelectValues(el);">Show selected values</button>
<div>
<h1 id="selections"></h1>
</div>
看一下这个例子: