简体   繁体   English

HTML多个选择选定的JS提交表格

[英]html multiple select chosen js submit form

I have this easy select in PHP as echo (using Chosen JS ): 我在PHP有这个简单的选择作为回显(使用Chosen JS ):

echo" <tr>
<th>By country:<br />
<select id=\"firstselect\" name=\"country[]\" 
    data-placeholder=\"Country...\" multiple class=\"chosen-select\">
        <option value=\"dontcare\">dontcare</option>";
        foreach ($states as $state) {
            echo "<option value=\"" . $state->stat .
                 "\" >" . $state->stat . "</option>";
         }
echo "</select> </th></tr>";

after submitting from and refreshing page values are not as selected. 从提交和刷新后,页面值未选定。

If i have select with only one choice this is working for me: 如果我只有一个选择,这对我有用:

var my_val = '<?=$_POST['price']?>'; 
$("#cenan").val(my_val).trigger("chosen:updated");

but i dont know how to set it as selected in case of array. 但我不知道如何将其设置为选定的数组。 Can you help me and show me some code? 您能帮我看看一些代码吗? I spent hours and hours without any result. 我花了几个小时没有任何结果。

You are POSTing the form data to the same page and then refreshing it, right? 您正在将表单数据发布到同一页面,然后刷新它,对吗?

If so then you can just change your PHP slightly to mark the chosen options as selected when the page refreshes by checking if its value exists in the $_POST['country'] array. 如果是这样,则可以通过检查$_POST['country']数组中是否存在PHP的值来稍作更改,以在页面刷新时将所选选项标记为已选中。

Also, as you are enclosing your echo output in double quotes there is no need to escape variables as PHP will parse them anyway, just use single quotes within the string where you want quotes in your HTML. 另外,由于将回声输出括在双引号中,因此无需转义变量,因为PHP仍会解析它们,只需在要在HTML中引号的字符串中使用单引号即可。 Much easier on the eye. 轻松得多。

foreach ($states as $state) {
    if ((!empty($_POST['country'])) && (in_array($state->stat, $_POST['country']))) {
        echo "<option value='$state->stat' selected>$state->stat</option>";
    } else {
        echo "<option value='$state->stat'>$state->stat</option>";
    }
}

Lets suppose you have HTML select like following : 假设您具有如下所示的HTML选择:

<select id='firstselect' multiple class="chosen-select" >
<option value='a'>A</option>
<option value='b'>B</option>
<option value='c'>C</option>
</select>

Here is the solution : 这是解决方案:

<?php
$arr = ['a','b']; // PHP Sample Array
?>


var js_json =  '<?php echo json_encode($arr); ?>';
var js_json_string = JSON.stringify(js_json);
var js_json_array = JSON.parse(js_json_string); // ['a','b']


// initialize
$("#firstselect").chosen();

// Loop for making HTML <select> options selected.
$.each(js_json_array,function(i,v){
$('#firstselect option[value=' + v + ']').attr('selected', true);
});

//Updating Chosen Dynamically
$("#firstselect").trigger("chosen:updated");

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

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