根据前一个输入文本填充第二个输入文本

时间:2015-07-14 08:39:33

标签: javascript php html

我正在构建一个表单,我希望在其中插入一些文本输入,一个数字,并在下一个输入文本中自动填充与DB中的数字匹配的名称。我已经测试过很多"解决方案"我在这里和其他网站上看到但没有工作。

我的脚本代码是:

$("#numero").blur(function () {
    $.post(convoc.php, { numero: $(this).val() }, function (data) {
        $("#nome").val(data);
    });
});

我的convoc.php代码:

if (@$_POST['numero'] != "")
        $numero = $_POST['numero'];
$query  = "SELECT Nome from ******* where Numero = $numero";
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);

    echo json_encode($row['Nome']);

(这很有效,因为我已经测试了回声并且打印了正确的名称)

我的第一个输入文字的ID是:" numero"并且第二个输入的id是" nome"。

我在脚本函数中出错了吗?

HTML代码为:

<body onload="load()" style="padding-top: 20px;">
    <form action="convoc.php" method="post">
        <div id="myform">
        <table align="center">
<tr>
            <td><input type="text" id="numero" name="numero"></td>
            <td><input type="text" id="nome" name="nome"></td>
        <td><input type="button" id="add" value="Convocar" onclick="Javascript:addRow()"></td>
    </tr>

</table>
</div>

</form>
</body>

js代码是:

function addRow() {

    var numero = document.getElementById("numero");
    var nome = document.getElementById("nome");
    var table = document.getElementById("myTableData");


    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);

    row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
    row.insertCell(1).innerHTML= numero.value;
    row.insertCell(2).innerHTML= nome.value;
}

function deleteRow(obj) {

    var index = obj.parentNode.parentNode.rowIndex;
    var table = document.getElementById("myTableData");
    table.deleteRow(index);

}

function load() {

    console.log("Page load finished");

}

(不,我在浏览器中没有收到任何错误)

2 个答案:

答案 0 :(得分:2)

更改脚本代码,如下所示。

  

第一个参数convoc.php应为'convoc.php'

$(function(){
    $("#numero").blur(function () {
        //use $.ajax
    $.ajax({
        url:'convoc.php',
        dataType:'json', //The datatype should be json because you are returning in json format
        data : {numero: $(this).val()},
        success:function(data){
        $("#nome").val(data.result);
        }
    });
    });
});

同样更改php代码如下。

echo json_encode(array("result"=>$row['Nome']));

答案 1 :(得分:0)

只需添加Json On:

$("#numero").blur(function () {
   $.post(convoc.php, { numero: $(this).val() }, function (data) {
     $("#nome").val(data);
  });
},"json");  // This Line