1

I have a form with input fields: name and description. The name field is a drop down. based on the name selected the description needs to change. I have made the drop down to populate the names already.

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

how do i change the description field based on the selected drop down?

<input type="text name="description" value="{{ $book->description }}>
Manas
  • 3,060
  • 4
  • 27
  • 55
  • 2
    You need to use jQuery onchange event and AJAX for that. – Rana Ghosh Mar 13 '17 at 08:43
  • thanks for the reply, do you know any examples? – Manas Mar 13 '17 at 08:46
  • 1
    Possible duplicate of [ajax call to populate form fields from database query when select value changes](http://stackoverflow.com/questions/19957823/ajax-call-to-populate-form-fields-from-database-query-when-select-value-changes) – Dariush Jafari Mar 13 '17 at 11:18

1 Answers1

1

Updated version:

You should store somewhere all $books as JavaScript variable. After that when you select name of the book, you can find book object (with description and other fields) and do whatever you want with them. You can achive by implementing these steps:

1) Make sure you have jQuery on your page

2) Add this JS code somewhere on the page (see comments)

<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>
Alexander Reznikov
  • 1,266
  • 1
  • 14
  • 23
  • thanks for the reply, with the above code i can only show the name of the book in the description but not the description of the book. – Manas Mar 14 '17 at 02:16
  • thx a lot Alexander Reznoik I made it work by using ajax requests – Manas Mar 15 '17 at 06:31