Development Blog

August 07, 2013
Preserve select multiple answers with jQuery on PHP $_Post.
jQuery
PHP



Working with Recaptcha security check, Salesforce or my custom PHP form, I came across that I needed to reload an array of selected answers within select multiple on my challenge page. Here is an exmaple if this was an input field:

RAW
<input name="First_Name" type="text" size="41" maxlength="60" value="<?php if (!empty($_POST['First_Name'])) { echo stripslashes(htmlentities($_POST['First_Name']));} ?>">

But with select mulitple, I used PHP to report back the array of answer(s) and then with jQuery scripting to reselect my answers.

RAW
<script language="JavaScript" type="text/javascript">
<!--

$(document).ready(function(){

<?php 

if (!empty($_POST['Cars'])) {
$multiplemenu = $_POST['Cars'];
echo "$('#Cars').val([";
foreach($multiplemenu as $key=>$value) { 
	unset($multiplemenu[$key + 1]); 
	$str[] = "\"" . "$value" . "\""; }
$result = implode(",", $str);
echo $result . "]).prop('selected', 'selected');" . PHP_EOL;
unset($str); }

?>

  });

// -->
</script>

<select id="Cars" multiple="multiple" name="Cars[]" size="8">
<option value="Acura">Acura</option>
<option value="Alfa Romeo">Alfa Romeo</option>
<option value="Aston Martin">Aston Martin</option>
// ...and so on
</select>



DEMO
First Name:


What auto maker(s) do you like?
(Ctrl-click to select multiple entries)

Home | Portfolio | Expertise | Clients | People | Contact | Privacy Policy | Copyright Policy
Copyright © 2024 Pinpoint Design LLC. All Rights Reserved.