简体   繁体   中英

html multiple select chosen js submit form

I have this easy select in PHP as echo (using 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.

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. 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 :

<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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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