2017-03-13 85 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

相关问题