如何根据从下拉列表中选择的值填充数据库中的完整表单输入字段
示例:在应用程序中,通过选择客户端名称,它将填充完整的表单输入字段,并在数据库中存储详细信息.
Sample Code:
<select name="client">
<option value="">-- Select Client Name -- </option>
<option value="1">John</option>
<option value="2">Smith</option>
</select>
<input name="phone" type="text" value="">
<input name="email" type="text" value="">
<input name="city" type="text" value="">
<textarea name="address"></textarea>
所有关于输入字段都需要填写客户端名称选择的值.
编辑:
我尝试使用AJAX但无法从文件中获取特定变量…下面是我的代码:
<script>
$(document).ready(function() {
$('#client').change(function() {
alert();
var selected = $(this).find(':selected').html();
$.post('get_details.PHP', {'client': selected}, function(data) {
$('#result').html(data);
});
});
});
</script>
在get_details.PHP文件中,我将不同的值存储在不同的变量中,但我不明白如何将它们转换为单个变量到主页面.
解决方法:
这只是一个调用自身的基本jQuery示例(当创建$_POST时脚本的顶部是活动的),我将其命名为index.PHP,如jQuery AJAX的url所示.如果需要,您可以使用两个单独的页面来执行此操作.只需将PHP与HTML / Javascript分开并更改url:’/ index.PHP’:
<?PHP
// This is where you would do any database call
if(!empty($_POST)) {
// Send back a jSON array via echo
echo json_encode(array("phone"=>'123-12313',"email"=>'test@test.com','city'=>'Medicine Hat','address'=>'556 19th Street NE'));
// Exit probably not required if you
// separate out your code into two pages
exit;
}
?>
<form id="tester">
<select name="client" id="client">
<option value="">-- Select Client Name -- </option>
<option value="1">John</option>
<option value="2">Smith</option>
</select>
<input name="phone" type="text" value="">
<input name="email" type="text" value="">
<input name="city" type="text" value="">
<textarea name="address"></textarea>
</form>
<!-- jQuery Library required, make sure the jQuery is latest -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
// On change of the dropdown do the ajax
$("#client").change(function() {
$.ajax({
// Change the link to the file you are using
url: '/index.PHP',
type: 'post',
// This just sends the value of the dropdown
data: { client: $(this).val() },
success: function(response) {
// Parse the jSON that is returned
// Using conditions here would probably apply
// incase nothing is returned
var Vals = JSON.parse(response);
// These are the inputs that will populate
$("input[name='phone']").val(Vals.phone);
$("input[name='email']").val(Vals.email);
$("input[name='city']").val(Vals.city);
$("textarea[name='address']").val(Vals.address);
}
});
});
});
</script>