更新版本:
你應該在一些地方保存所有$書籍JavaScript變量。之後,當你選擇書的名字時,你可以找到書對象(帶有描述和其他字段),並隨你做他想做的事情。您可以通過執行這些步驟achive:
1)請確保您有jQuery的你的頁面
2)添加這個地方的js代碼的網頁上(見註釋)
<script type="text/javascript">
// 2.1 "Store" all books in some place on the page, for example, you can pass PHP variable into JS variable like this
var books = <?= json_encode($books); ?>;
/*
* 2.2 Create function for search book by its name
* (if each value of the field "name" in the $books is unique) or by some unique field, for example, "id"
*/
// get book by name
var getBookByName = function (bookName) {
if (typeof books === 'object') {
for (var key in books) {
if (typeof books[key].name !== 'undefined' && books[key].name === bookName) {
return books[key];
}
}
}
return false;
}
$(document).ready(function() {
// add event listener on the select with the attribute name="name"
$('select[name="name"]').on('change', function (e) {
// get book by selected name of the book
var selectedBook = getBookByname($(e.target).find('option:selected').text());
if (selectedBook) {
// set new value for the input with the attribute name="description"
$('input[name="description"]').val(selectedBook.description);
}
// we can't find book by it's name
else {
alert("Sorry, we can find description for this book");
}
});
});
</script>
您需要使用jQuery onchange事件和AJAX。 –
感謝您的回覆,你知道任何例子嗎? – Mikethetechy
[ajax調用填充表單字段從數據庫查詢時選擇值更改]可能重複(http://stackoverflow.com/questions/19957823/ajax-call-to-populate-form-fields-from-database-query-當選擇值更改) –