2010-07-11 73 views
1

好吧,基本上我試圖做的是使用文本框的值(大多數情況下是自動完成的)用從數據庫中提取的數據填寫另一個文本框。使用jQuery「自動填充」第二個文本框,根據第一個輸入

用戶將在一個框中輸入名稱,一旦該輸入失去焦點,則會自動填充名稱的相關電子郵件地址。

我已經看到了幾個不同的jQuery插件,它們與我想要的相似,但只適用於選擇(我不想要,因爲名稱可能會添加一個新名稱)。

我知道有人會說:「嗯,你爲什麼不從數據庫中提取姓名和電子郵件地址,並在頁面加載時填寫表單。」答案是:因爲這個名字將被即時添加(當您添加一個新訂單時,請考慮訂單跟蹤軟件的界限)。

我使用PHP,MySQL,當然還有jQuery。

在此先感謝。

回答

3

你並不需要一個插件來做到這一點,只是模糊事件

$("#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); 
}); 
+0

這實際上看起來是最簡單的方法。非常小的代碼,甚至更少的代碼更改(對我的PHP),因爲我已經使用JSON的自動完成。 – Micheal 2010-07-11 18:30:30

1

下面是它可能看起來像客戶端:

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

在「名稱」字段失去焦點發送帶有設置爲「名稱」字段中的參數「名」來lookupemail.php的請求。請求返回時,將其放入「電子郵件」字段。

+0

不使用'的.text()'上inputboxes ....使用'.VAL()',而不是... :) – Reigel 2010-07-11 02:58:40

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所需要的數據,第二輸入框... 。

+0

感謝你爲這個。我想如果我昨天晚上不那麼累,我可以找到這個:http://stackoverflow.com/questions/558445/dynamically-fill-in-form-values-with-jquery 幾乎完全是我想要,而且我看到你的答案非常相似。 – Micheal 2010-07-11 18:26:32

相關問題