Francisunoxx Francisunoxx - 4 months ago 6
PHP Question

How to passed multiple selected list into variable?

I'm trying to passed my selected list in variable. Like this but it prints me a

undefined
value.

function showUserOptions(a)
{
var b = console.log(a[a.selectedIndex].value);
alert (b);
}


I can get the value using
console.log
but I want the user click the selected list the value inside in variable will changed.

Form:

<div class = "form-group">
<label for = "to" class = "control-label">To:</label>
<select onChange = "showUserOptions(this)" name = "to" class = "form-control" multiple>

@foreach ($result as $list)
<option value = "{{ $list->id }}">{{ $list->username }}</option>
@endforeach

</select>
</div>


Controller:

public function getDocuments()
{
$result = DB::table('users')->where('id', '!=', Auth::id())->get();

return view ('document.create')->with('result', $result);
}

Answer

provide a id to your drop down, and its name will be an array so that it can hold multiple values like:

    <select name="myDropDown[]" id="myDropDown" class= "form-control" multiple>

        @foreach ($result as $list)
            <option value = "{{ $list->id }}">{{ $list->username }}</option>
        @endforeach

    </select>

 $('#myDropDown').change(function(){
        var selectedVal = $(this).val();    
     // it will return the selected values in an array
 });

Try this, it work.

Comments