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.
- First I fetch data with insurance
private- working fine - Then fetch row with insurance
public- working fine - Again fetch data with
private- 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
CodePudding user response:
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);
}
}
CodePudding user response:
I resolved my issue adding a single line code. The actual problem is, the selected option is remains as selected always. If I select one option and then the second both will be marked as selected. So On the next calls the first option will be showing because both are selected. So I have added code to remove the selection before assign the selection to new option.
Here is my corrected code:
if(data['insurance'] != ''){ console.log(data['insurance']);
$('#insurance').find('option:selected').attr('selected', false);
$('#insurance > option[value="' data["insurance"] '"]').attr('selected',true);
}
