douzhang3822 2015-02-26 05:22
浏览 16
已采纳

Jquery Ajax无法获得当前的焦点输入元素

I have form that has two kinds of input field, 1) input field for ID, 2) input field for name. I already have a mysql database with a table filled with ID and name data. What I want to do is when I type an ID number in the input field for ID, and when it loses focus, the jquery script will automatically fill the input field for name according to the ID number in the database. So my html input form is something like this:

html :

<input type='text' name='id' class='input_id'>
<input type='text' name='name' class='input_name'>
<br>
<input type='text' name='id'>
<input type='text' name='name'>

jquery script:

$(document).ready(function) {
    $('.input_id').blur(function() {
        $.post('search_name.php',
        {
            id: $('.input_id').val()
        },
        function(data) {
            $('.input_name').val(data);
        });
    });
});

php (search_name.php) code :

<?php
$con = mysqli_connect('localhost','root','','database');
$id = $_POST['id'];
$sql = "SELECT * FROM table WHERE id='$id'";
$query = mysqli_query($con, $sql);
$result = mysqli_fetch_array($query);
$name = $result['name'];

echo $name;
mysqli_close($con);
?>

The problem is in one form, I will have 20 rows of ID and name input field, how do I modify my jquery script so that when ID input field in row 1 loses focus, it will only auto-fill name input field in row 1, the one in row 2 will only auto-fill name input field in row 2 and so on, rather than writing the same script 20 times.

I tried using traversing method such as (this) and (next), but I could not seem to get it working. I also tried using (:focus) method too, I am not sure whether I use it wrongly or it is not meant for this.

All suggestions are welcomed. Thx in advance.

  • 写回答

1条回答 默认 最新

  • douhan1860 2015-02-26 05:28
    关注

    Assuming they are siblings, use this and next()

    $('.input_id').blur(function() {
        var inp = $(this);
        $.post('search_name.php',
        {
            id: inp.val()
        },
        function(data) {
            inp.next('.input_name').val(data);
        });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?