jQuery <select> Manipulation: Fill multiple <select> with JSON data and set second <select> default on POST
« Return to ArticleDemo
jQuery
function getSubs(id, selected)
{
$.ajax({
type: "GET",
dataType: "json",
cache: false,
url: 'json-default.php?id=' + id,
timeout: 2000,
error: function() {
alert("Failed to submit");
},
success: function(data) {
// Clear
$("select#sub_category_post option").remove();
$.each(data, function(i, j){
var row = "";
$(row).appendTo("select#sub_category_post");
});
// Set the selected value
$("select#sub_category_post").val(selected);
}
});
}
$(document).ready(function(){
$("select#category_post").change(function(){
// Send the request and update dropdown
getSubs($(this).val());
});
<?php
// Set the sub category
if ($_POST)
{
?>
getSubs(<?php echo $_POST['category_post']; ?>, <?php echo $_POST['sub_category_post']; ?>);
<?php
}
?>
});
HTML
<select name="category_post" id="category_post">
<option value="">-- Select Type --</option>
<?php
// Create array of animal types
$animals = array(
1 => 'Dog',
2 => 'Cat'
);
foreach ($animals as $key => $val)
{
if ($_POST['category_post'] == $key)
{
?>
<option value="<?php echo $key; ?>" selected=""><?php echo $val; ?></option>
<?php
}
else
{
?>
<option value="<?php echo $key; ?>"><?php echo $val; ?></option>
<?php
}
}
?>
</select>
<select name="sub_category_post" id="sub_category_post">
<option value="">-- Select First Value --</option>
</select>
JSON AJAX Script, json-default.php
$json = array();
if ($_GET['id'] == 1)
{
$json[] = array(
'value' => '1',
'text' => 'Staffordshire Bull Terrier'
);
$json[] = array(
'value' => '2',
'text' => 'Labrador Retriever/American Pit Bull Mix'
);
$json[] = array(
'value' => '3',
'text' => 'German Short Hair Pointer'
);
}
elseif ($_GET['id'] == 2)
{
$json[] = array(
'value' => '4',
'text' => 'Domestic Medium Hair'
);
}
echo json_encode($json);
Donate
If you found this article useful and would like to see more like it this please consider making a donation.
