i need some clarification on how to populate select(s) with data from mysql. Basically what I am trying to do is:
There will be a first select box with some data in it.
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
when the user selects a option in开发者_如何学JAVA the first select, there is a second select below that, which should reflect the values according to the selection made in the first select.
<select>
<option>1.1</option>
<option>1.2</option>
<option>1.3</option>
</select>
The data is commin from MySQL. I am not sure if need to post to same page, but if I do, how to retain the values alredy selected in the previous select boxes? do i need to use javascript?
any help?
Thanks.
You should use javascript so you don't need a page refresh. I just re-read your question and I'll have a solution involving an AJAX request in a second to pull dynamic data:
HTML
<select name="select1" id="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="select2" id="select2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
jQuery
<script type="text/javascript">
$(document).ready(function() {
$('#select1').change(getDropdownOptions);
});
function getDropdownOptions() {
var val = $(this).val();
// fire a POST request to populate.php
$.post('populate.php', { value : val }, populateDropdown, 'html');
}
function populateDropdown(data) {
if (data != 'error') {
$('#select2').html(data);
}
}
</script>
populate.php
<?php
if (!empty($_POST['value'])) {
// query for options based on value
$sql = 'SELECT * FROM table WHERE value = ' . mysql_real_escape_string($_POST['value']);
// iterate over your results and create HTML output here
....
// return HTML option output
$html = '<option value="1">1</option>';
$html .= '<option value="b">B</option';
die($html);
}
die('error');
?>
精彩评论