简体   繁体   中英

How to make my option a default so if I clear my drop-down it is populated by the default

I want to make one option the default value so if I clear my drop-down it is populated by the default.

This is my code:

<script language="JavaScript">
function getEnvNames(result){
    $("#environmentName").empty();

var data = JSON.parse(result);
        $.each(data, function(key, value)
        {
            $("#environmentName").append("<option>" + value.name +" - "+ value.purpose + "</option>");

        });

}

This is my HTML:

<select class="body" name="environmentName" id="environmentName" class="body">                                                                                                                                                  
                        <option selected="selected" disabled="disabled">Select An Environment</option>                                                                                                                                                          
                        </select>

If default selected value is select an environment , then use append function:

$('#environmentName').empty().append('<option selected="selected" disabled="disabled">Select An Environment</option>');

Or if you don't want to remove the selected value (once the user changes the option)

$("#environmentName").children().not($("#environmentName option:selected")).remove();

At the time of clear your select box put a empty option will solve your problem

function getEnvNames(result){
 $("#environmentName").html('<option value="" >  Select An Environment </option>');

data = JSON.parse(result);
        $.each(data, function(key, value)
        {
            $("#environmentName").append("<option>" + value.name +" - "+ value.purpose + "</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