2017-03-13 83 views
1

我有一個輸入字段的表單:名稱和說明。名稱字段是一個下拉菜單。根據所選名稱的描述需要改變。我已經完成了下拉式填充名稱。如何根據下拉選擇填充表單域?

<form> 
<select name="name" > 
@foreach($books as $book) 
<option value="{{$book->name}}">{{$book->name}}</option> 
@endforeach 
</select> 

如何根據所選下拉菜單更改說明字段?

<input type="text name="description" value="{{ $book->description }}> 
+2

您需要使用jQuery onchange事件和AJAX。 –

+0

感謝您的回覆,你知道任何例子嗎? – Mikethetechy

+1

[ajax調用填充表單字段從數據庫查詢時選擇值更改]可能重複(http://stackoverflow.com/questions/19957823/ajax-call-to-populate-form-fields-from-database-query-當選擇值更改) –

回答

1

更新版本:

你應該在一些地方保存所有$書籍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> 
+0

感謝您的答覆,與上面的代碼我只能在說明書中顯示書的名稱,而不是本書的描述。 – Mikethetechy

+0

我已更新我的答案,請嘗試此操作。 –

+0

thx很多亞歷山大Reznoik我使它通過使用Ajax請求 – Mikethetechy

相關問題