开发者

Using jQuery to "auto-fill" a second text box, based on input from the first

Alright, so basically what I'm trying to do is use the value (which in most cases is autocompleted) of a text box to fill in another text box with data pulled from the database.

The user will input a name in one box and once that input loses focus, a second is auto populated with the name's associated email address.

I've seen a few different jQuery plugins that are similar to what I want, but only work for selects (which I do not want since there is the possibility that the name will be a new one to be added).

I know someone is going to say something along the lines of: "Well, why don't you just pull the name and email address from the database and populate the form on page load." The answer: because the name will be added on the fly (think along the lines of an order tracking software, when you add a new order).

I'm using PH开发者_C百科P, MySQL, and of course jQuery.

Thanks in advance.


You don't need a plugin to do that, just call $.post with the blur event

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

In you php file, you'll be able to get the name with $_POST["name"] and to send the email back to the javascript, just echo it

If you need to load more data than only a string, you should use json_encode() to encode an array

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

And change your post call to this:

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


you could do something like this...

$('#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... 
       }
   });
});

from that above codes of jQuery, you could do $_GET['foo'] in php... and you should echo the needed data for the second inputbox....


Here's what it might look like client side:

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

When the 'name' field loses focus send a request to lookupemail.php with the parameter 'name' set to the 'name' field. When the request is returned, put it in the 'email' field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜