根据databse php中的select box选项获取输入字段值

时间:2016-03-22 10:30:59

标签: php jquery ajax

我有一张表格。它有选择框。 根据从选择选项中选择的值,我想填充表单的其余文本字段。

以下是表格:

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script type="text/javascript">
$('#test').change(function(){
var val=document.getElementsById('test').value;
$.ajax({
    type: "GET",
        url: "get_user.php",
        data: {id:val},
        success:function()
        {


        }
            })

})
</script>


<select name="test" id="test" >
<option value="user1">user1</option>
<option value="user2">user2</option>
<option value="user3">user3</option>
<option value="user4">user4</option>
<option value="user5">user5</option>
</select>
<input type="text" placeholder="Address"/>
<input type="text" placeholder="Name"/>
<input type="text" placeholder="Contact"/>

如果选择“user1”,则应调用ajax并从数据库获取“user1”的值,然后在文本字段中显示该值。

2 个答案:

答案 0 :(得分:0)

试试这个......

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script type="text/javascript">
$('#test').change(function(){
    var val=document.getElementsById('test').value;;
    $.ajax({
        type: "GET",
            url: "get_user.php",
            data: {id:val},
            type: 'post',
            dataType: "json",
            success:function(data)
            {
                 $("#add").val(data[0]);
                 $("#name").val(data[1]);
                 $("#cnt").val(data[2]);
            }
    })
})
</script>


<select name="test" id="test" >
<option value="user1">user1</option>
<option value="user2">user2</option>
<option value="user3">user3</option>
<option value="user4">user4</option>
<option value="user5">user5</option>
</select>
<input type="text" placeholder="Address" id="add"/>
<input type="text" placeholder="Name" id="name"/>
<input type="text" placeholder="Contact" id="cnt"/>

希望它会对你有所帮助。

答案 1 :(得分:0)

HTML:

<input type="text" placeholder="Address" id="address"/>
<input type="text" placeholder="Name" id="name" />
<input type="text" placeholder="Contact" id="contact"/>

JS:

<script type="text/javascript">
    $('#test').change(function(){
    var val=$(this).val();
    $.ajax({
        type: "GET",
            url: "get_user.php",
            data: {id:val},
            success:function(data)
            {
            var result = $.parseJSON(data);
            $("#address").val(result.address);
            $("#name").val(result.name);
           $("#contact").val(result.contact);     
            }
         })

    </script>

PHP:

    //fetch data accorind to id
    $array= array();
    $array["name"] ="name";// user name
    $array["contact"] ="contact";// user contact
    $array["address"] ="address";// user address
    echo json_ecode($array);