I was developing Laravel project and what I want to achieve is that when a user picks a certain value in dropdownlist, it should influence other dropdownlists in the view, that is, if user selects Income in the first dropdown then Expense dropdownlist should be disabled or something like that Controller
> public function create()
> {
> $income = Income::pluck('title', 'id');
> $expense=Expenses::pluck('title', 'id');
> return view ('IncomeExpense.create', compact('income','expense'));
> }
View
<div class="form-group">
> {{Form::label('IncomeExpense', 'Income&Expense')}}
> {{Form::select('IncomeExpense', array('E' => 'Expense', 'I' => 'Income'),null,['class'=>'form-control'])}}
> </div>
> <div class="form-group">
> {{Form::label('', 'Income')}}
> {{Form::select('IncomeId', $income,null,['class'=>'form-control'])}}
> </div>
> <div class="form-group">
> {{Form::label('', 'Expense')}}
> {{Form::select('ExpenseId', $expense,null,['class'=>'form-control'])}}
> </div>
I got a solution for you. But you may use select('title', 'id')->get()
instade of pluck('title', 'id')
. Because pluck
is generally used for geting a single column value.
Now, for your solution, you can use a little bit of JavaScript
. For that, you have to give an id
to your select
tags each. Like
Income Dropdown
<select class="form-control select2" id="income" onChange="validate()">
<option value="selectincome">--- selectincome ---</option>
@foreach($incomes as $income)
<option value="{{$income['id']}}">{{$income['title']}}</option>
@endforeach
</select>
And Expense Dropdown
<select class="form-control select2" id="expense" onChange="validate()">
<option value="selectexpence">--- selectexpence ---</option>
@foreach($expenses as $expense)
<option value="{{$expense['id']}}">{{$expense['title']}}</option>
@endforeach
</select>
Now, the validate()
method
JavaScript
function validate(){
var ddlIncome = document.getElementById("income");
var ddlExpence = document.getElementById("expense");
var selectedValueIncome = ddlIncome.options[ddlIncome.selectedIndex].value;
var selectedValueExpence = ddlExpence.options[ddlExpence.selectedIndex].value;
if (selectedValueIncome != "selectincome"){
document.getElementById("expense").disabled=true;
}
else if (selectedValueIncome != "selectexpence"){
document.getElementById("income").disabled=true;
}
}
Hope this helps.