I'm using Laravel in my application and have a question about jquery selection. In my case, I want to match an option.value with an ID and if it is matched then mark option as selected. Here is my code:
<select id="class" name="class" class="custom-select form-control" required>
@foreach ($classes as $class)
<option value="{{ $class->id }}"
{{ old('class_id') ?? $subject->class_id == $class->id ? 'selected' : '' }}>
{{ $class->name }}</option>
@endforeach
</select>
<select id="section" name="section" class="custom-select form-control" required>
<option value="">- -</option>
</select>
and in my javascript, which is loading in the end of the page:
$(document).ready(function(){
var class_id = $('#class option:selected').val();
var section_id = $('#hidSectionID').val();
fetchSections(class_id);
setSection(section_id);
});
fetchSections(class_id) is my ajax function which is working fine and appending *select[name="section"] *options with this response.
<option value="1">Option 1</option><option value="2">Option 2</option>
But my second function which is for setting the section option as selected if it is matched with var section_id (which is coming from Laravel controller) is not working. I tried with different ways but it is not working:
function setSection(section_id){
// Try # 1
$("select#section option[value="+section_id+"]").prop("selected", true);
// Try # 2
$("#section").val(section_id);
// Try # 3
$("#section > option").each(function(){
if($(this).val()===section_id){
$(this).attr("selected","selected");
return false;
}
});
// Try # 4
$.each($("#section option"), function(){
// alert($(this).text() + " - " + $(this).val());
});
}
I hope, I've written enough code to understand this problem. Any help would be appreciated.