简体   繁体   中英

setting an option selected is not working

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.

As @freedomn-m mentioned, I've called my setSection function right after calling an ajax fetchSection function. So I've now added jquery delay() function to my code.

$("#section").delay(1000).queue(function(){
    $(this).val(section_id); 
    $(this).dequeue();
}); 

And it works perfectly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM