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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c