I have a dropdown with two options public
and private
. I am fetching data from database using ajax and showing in the form fields. So I have written script in JQuery to set the value to be selected. But it working properly only twice, like only once for public
and first time for private
.
Here is my code
HTML
<select name="insurance" class="form-select" id="insurance" required>
<option value="">--Select--</option>
<?php $insurance = App::make("App\Http\Controllers\AppointmentsController")->getInsurance(); ?>
@foreach($insurance as $ins)
<option value="{{ $ins->id }}">{{ $ins->insurance }}</option>
@endforeach
</select>
JQuery
if(data['insurance'] != ''){
console.log(data['insurance']); // showing correct value
$('#insurance > option[value="'+data["insurance"]+'"]').attr('selected',true);
}
Here data['insurance']
is my result array value from ajax.
private
- working finepublic
- working fineprivate
- not working (showing the last status only)If try to fetch records with any value - not working.
Only first two times, it is working properly
You should also remove the attribute selected of the other option via jquery.
As I see in the first occasion gets selected, then since both of the are selected the first one will stay selected in the form.
Try something like this:
if(data['insurance'] != ''){
if(data['insurance'] == 'public'){
$('#insurance > option[value="private"]').removeAttr('selected');
$('#insurance > option[value="public"]').attr('selected', true);
}
else{
$('#insurance > option[value="public"]').removeAttr('selected');
$('#insurance > option[value="private"]').attr('selected', true);
}
}