如何根據從下拉列表中選擇的值填充數據庫中的完整表單輸入字段
示例:在應用程序中,通過選擇客戶端名稱,它將填充完整的表單輸入字段,并在數據庫中存儲詳細信息.
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示例(當創(chuàng)建$_POST時腳本的頂部是活動的),我將其命名為index.php,如jQuery AJAX的url所示.如果需要,您可以使用兩個單獨的頁面來執(zhí)行此操作.只需將PHP與HTML / Javascript分開并更改url:’/ index.php’:
<?php// This is where you would do any database callif(!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>
來源:https://www.icode9.com/content-1-292101.html
聯系客服