繁体   English   中英

根据mysql值选择多个选择表单值

[英]Multiple select form values selected based on mysql values

我在引导模态中有一个带有多重选择的表单:

            <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');
});

是否还有一种方法可以获取以这种方式选择的多重选择的值?

解:

var product = "product1, product2, product3";
var product_array = product.split(", ");
$(".modal-body #product").val( product_array );

演示:

http://jsfiddle.net/8WhrA

使用循环:

// 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;

您必须在必须选择的选项内添加selected,如下所示:

<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代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM