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

标签 javascript php html

我正在构建一个表单,我想在其中插入一些文本输入、一个数字,并在下一个输入文本中自动填充与数据库中的数字匹配的名称。我已经测试了许多我在这里和其他网站上看到的“解决方案”,但没有一个有效。

我的脚本代码是:

$("#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']);

(这很好用,因为我已经测试了 echo 并且它正在打印正确的名称)

我的第一个输入文本的 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");

}

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

最佳答案

修改脚本代码如下。

The first parameter convoc.php should be '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']));

关于javascript - 根据前一个输入文本填充第二个输入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31401785/

相关文章:

php - EAV、架构更改、Json?

javascript - 页面加载后如何删除或隐藏div

html - 选择最后一个连续的 sibling

javascript - 超时时设置 jquery loader (window.setTimeout)

javascript - 相对路径中的Angular 2 img src

javascript - KnockoutJS : Using 'html' binding, 新元素未绑定(bind)

javascript - 在 AngularJS 中加载本周的数据

php - 用于在具有 GROUP_CONCAT 的表中显示父子的 MySQL 查询

php - 使用 dropzone 在一个请求中上传多个文件时遇到问题

javascript - onClick 在 :active is set on img 时调用第二个 Click