简体   繁体   中英

How to show selected options from dropdown in javascript

Hi guys i have written some javascript code to display some values depend on another dropdown. So now i would like to display those selected values in my edit page..

Here is my code:

function getSubjectsTopics(subject_id)
{
    if(subject_id) {
        loading_show();


        axios.get("/master/topic/get-topic-by-subject-id/" + subject_id)
        .then(function(response) {
            var optionHtml = '<option value="0">Parent</option>';
            if(response.data.status) {
                $.each(response.data.subject_topics, function(i,v) {
                    optionHtml += `<option value="${v.id}" >${v.name}</option>`;
                }

            $("#ddl_topic_type").html(optionHtml).attr('disabled', false).select2();
            loading_hide();
        })
        .catch(function(error) {
            loading_hide();
            console.log(error);
            Swal.fire({
                type: 'error',
                title: 'Oops...',
                text: 'Something went wrong!'
            })
        })
    } else {
        $("#ddl_topic_type").attr('disabled', true);
    }
}

Can some one help me how can i add my selected code in optionhtml variable.TIA

In the $.each block, you can use a ternary operator and add the "selected" keyword based on the selection criteria.

First assign a boolean to isSelected variable after checking whether it should be selected or not. Then add the selected keyword into the template literals using a ternary operator

optionHtml += `<option value="${v.id}" ${isSelected ? 'selected' : ''} >${v.name}</option>`;

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