我在bootstrap模式中有一个带有多个select的表单:
<label>Product:</label>
<select name="product[]" multiple="multiple" id="product">
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4">Product 4</option>
<option value="5">Product 5</option>
<option value="6">Product 6</option>
</select><br />
我会将我的数据从这个表单保存到Mysql数据库中的单个字段,如1,4,6(我用implode来做这个)
现在当我调用一个模态来编辑我的表单时,我希望看到选择值为1,4和6的多重选择。
有没有办法实现这个目标?
修改
感谢您的快速解答!一切都很有用,但是当我使用很多模态时,也许最好用javascript调用它们并填写表格中的字段:
的 HTML: 的
<a href='#afvalstoffen-edit' class='afvalstoffen-edit' data-toggle='modal' data-id='$id' data-product='$product'......
的 JAVASCRIPT: 的
$(document).on("click", ".afvalstoffen-edit", function () {
var data_id= $(this).data('id');
var product= $(this).data('product');.....
然后填写模式中的表单,如:
......
$(".modal-body #data_id").val( data_id);
$(".modal-body #product").val( product);
$('#afvalstoffen-edit').modal('show');
});
是否还有一种方法可以通过这种方式获取多重选择的值?
SOLUTION:
var product = "product1, product2, product3";
var product_array = product.split(", ");
$(".modal-body #product").val( product_array );
DEMO:
答案 0 :(得分:3)
使用循环:
// Grab the selected values from the database, if its a string, use 'explode()' to make them an array
$selectedValues = array(1, 3, 5);
$selectOptions = array(
'1' => 'Product 1',
'2' => 'Product 2',
'3' => 'Product 3',
'4' => 'Product 4',
'5' => 'Product 5'
);
$html = '<select>';
foreach($selectOptions as $key => $value)
{
$selected = in_array($key, $selectedValues) ? 'selected ' : '';
$html .= '<option ' . $selected . 'value="' . $key . '">' . $value . '</option>';
}
$html = '</select>';
echo $html;
答案 1 :(得分:2)
您必须在必须选择的选项中添加所选内容,如下所示:
<label>Product:</label>
<select name="product[]" multiple="multiple" id="product">
<option value="1" selected>Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4" selected>Product 4</option>
<option value="5">Product 5</option>
<option value="6" selected >Productv6</option>
</select><br />
因此,如果必须在默认情况下选择,请将一些php代码添加到相应的标记中。