【问题标题】:Using jQuery to "auto-fill" a second text box, based on input from the first根据第一个文本框的输入,使用 jQuery “自动填充”第二个文本框
【发布时间】:2011-03-14 09:27:33
【问题描述】:

好的,所以基本上我要做的是使用文本框的值(在大多数情况下是自动完成的)用从数据库中提取的数据填充另一个文本框。

用户将在一个框中输入一个名称,一旦该输入失去焦点,第二个输入框会自动填充该名称的关联电子邮件地址。

我见过一些不同的 jQuery 插件,它们与我想要的类似,但仅适用于选择(我不想要,因为名称可能是要添加的新名称)。

我知道有人会说:“好吧,你为什么不直接从数据库中提取姓名和电子邮件地址,然后在页面加载时填充表单。”答案是:因为名称会即时添加(当您添加新订单时,请按照订单跟踪软件的思路思考)。

我正在使用 PHP、MySQL,当然还有 jQuery。

提前致谢。

【问题讨论】:

    标签: php jquery autofill


    【解决方案1】:

    您不需要插件来执行此操作,只需使用模糊事件调用 $.post

    $("#name").blur(function () {
        $.post(your_php_file, { name: $(this).val() }, function (data) {
            $("#email").val(data);
        });
    });
    

    在您的 php 文件中,您将能够使用 $_POST["name"] 获取名称并将电子邮件发送回 javascript,只需回显即可

    如果你需要加载比字符串更多的数据,你应该使用 json_encode() 来编码一个数组

    $name = $_POST["name"];
    //pick data from db
    $arr = array("email"=>$email, "otherstuff"=>$otherstuff);
    echo json_encode($arr);
    

    并将您的帖子调用更改为:

    $.post(your_php_file, { name: $(this).val() }, function (data) {
        $("#email").val(data.email);
        $("#otherstuff").val(data.otherstuff);
    });
    

    【讨论】:

    • 这实际上看起来是最简单的方法。非常少的代码,甚至更少的代码更改(对我的 PHP),因为我已经使用 JSON 进行自动完成。
    【解决方案2】:

    你可以做这样的事情......

    $('#input_1').blur(function(){ // blur event, when the input box loses focus...
       var data = this.value;     // get the data of the this inputbox, in our case id="input_1"
       $.ajax({
           url: 'some/url.php', // your php that is used to query MySql
           method: 'get',       // method to be used , get/post
           data: {
               'foo' : data // the data to be passed, e.g. ?foo=data
           }
           success : function(msg){   // when connection to server is successful, msg is the data returned from 'some/url.php'
               $('#input_2').val(msg); // populate the second inputbox with msg... 
           }
       });
    });
    

    从上面的jQuery代码中,你可以在php中做$_GET['foo']...你应该echo第二个输入框所需的数据......

    【讨论】:

    【解决方案3】:

    这可能是客户端的样子:

    $('#name').blur(function(){
      str = $('#name').val()
      $.get("lookupemail.php", { name: str}, function(data){
        $('#email').val( data );
      });      
    });
    

    当'name' 字段失去焦点时,向lookupemail.php 发送请求,并将参数'name' 设置为'name' 字段。当请求返回时,将其放在“电子邮件”字段中。

    【讨论】:

      猜你喜欢
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-16
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2017-07-23
      相关资源
      最近更新 更多