如何根据下拉选择填充表单域?

时间:2017-03-13 08:41:25

标签: javascript php ajax forms laravel

我有一个包含输入字段的表单:名称和描述。名称字段是下拉列表。根据所选名称,描述需要更改。我已将下拉列表填入名称。

<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 }}>

1 个答案:

答案 0 :(得分:1)

更新版本:

你应该将所有$ books存储在JavaScript变量中。之后,当您选择书籍的名称时,您可以找到书籍对象(包含描述和其他字段)并随意使用它们。您可以通过实施以下步骤来实现:

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>