通过Dropdown Jquery填充文本输入

时间:2012-05-21 13:37:00

标签: php jquery mysql

我从MYSQL数据库中提取数据以填充下拉列表

<td class="<?php print $Bank_ca_error;?>">Bank Name</td> <td> <select name="Bank" id="Bank" tabindex=24 style="color: <?php print $TextColour;?>"/> <option><?php print $_SESSION['Bank_ca'] ;?></option> <?php //Get Data to populate drop down $BankQuery = "SELECT BankName FROM tblbank ORDER BY BankName"; $BankResult = mysql_query ($BankQuery); While($nt=mysql_fetch_array($BankResult)) { print"<option $nt[BankName]>$nt[BankName]</option>"; } ?> </select> </td> 

我想根据选中的值填充文本输入。所以基本上从列表中选择银行,让它在文本输入中自动填充通用分支代码。

我看到了一个使用Jquery的例子,但是当谈到这个时我就是一个完整的菜鸟,我无法让它正常工作

我在Head部分添加了以下内容

<script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery('#Bank').live('change', function(event) { $.ajax({ url : 'getData.php', type : 'POST', dataType: 'json', data : $('#myform').serialize(), success: function( data ) { for(var id in data) { $(id).val( data[id] ); } } }); }); }); </script> 

然后我将其添加到getData.php文件中

<?php include "../../../includes/dbinfo.inc"; //Connect to database     mysql_connect($db_host, $db_username, $db_password); @mysql_select_db($db_database) or     die("Unable to select database"); $BankName = $_POST['Bank']; // Selected Bank $query = "SELECT * FROM tblbank WHERE BankName ='{$BankName}'"; $result = mysql_query($query); $row = mysql_fetch_array($result) $BranchCode = $row['UniversalCode']; $arr = array(     'input#BranchCode' => $BranchCode ); echo json_encode( $arr ); ?> 

并将以下内容添加到输入和下拉菜单

周围
<form id='myform'> </form>

我尝试在site的其他地方使用解决方案,但无法使其正常工作

非常感谢您的协助

1 个答案:

答案 0 :(得分:0)

如果我理解你正在尝试做什么,那么你不需要ajax,尝试这样的事情

<?php
include "../../../includes/dbinfo.inc"; 
//Connect to database
mysql_connect($db_host, $db_username, $db_password); @mysql_select_db($db_database) or die("Unable to select database");

$res = mysql_query("SELECT UniversalCode, BankName FROM tblbank ORDER BY BankName");
while($row = mysql_fetch_assoc($res)) {
    // associative array of banks
    $banks[$row['UniversalCode']] = $row['BankName'];
}
?>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
    $('#Bank').change( function() {
        // enter in an empty field code of the selected bank
        $('#UniversalCode').val( $(this).val() );
    });
});
</script>
<td class="<?php print $Bank_ca_error;?>">Bank Name</td> 
<td> 
<select name="Bank" id="Bank" tabindex=24 style="color: <?php print $TextColour;?>"/> 
    <? foreach($banks as $code=>$name) { ?>
        <option value="<?=$code?>"><?=$name?></option> 
    <? } ?>
</select>
<input value="" id="UniversalCode">
</td>