How to create an empty / null value in select dynamically?

0

I have a select of cities that is populated dynamically with the query returned in the databases, however when the values in the option is played the default value empty some prevents select an empty line. See:

% empty%:

Selectsupplied:

HerearecodesthatsupplySelect:

functionfunc(){if(ajax.readyState==4&&ajax.status==200){eval(ajax.responseText);if(dados.erro){alert(convertHtml(dados.erro));}else{varvazio="";
        var cidades =  dados.split(",");
        var html = "";

    for(var i = 0; i < cidades.length; i++)
    {
        html =  '<option>'+cidades[i]+'</option>';
        document.getElementById('cidade').innerHTML += html;
    }
       }
    }     
}

<label for="cidade">Cidade: <br>
                        <select name="cidade" id="cidade" value="<?=$MunNome?>" class="campos_menu" style="width:110px;">
                         <option value=""></option>
                        </select>
                        </label>
    
asked by anonymous 24.05.2018 / 14:09

4 answers

1

Just create a option with empty text and add to the end of for in select :

for(var i = 0; i < cidades.length; i++) {
   .....
 }

var select = document.getElementById('cidade');
var opt = new Option('', '');
select.insertBefore(opt,  select.options[0]); 

Just to clarify, option could be added simply like this:

select.add(opt);

But that would add in the end as the last. As the question speaks of an empty option, which would be the first one, with the same goal as a "- select -", I used insertBerfore , which will insert before an existing option. Since the second parameter is select.options[0] , which returns the first element (index 0), it will insert the new option before it, which will then be the first option of select .

    
24.05.2018 / 14:56
1

Well, I made an adjustment so that I could test here and the form below is working perfectly, I hope the following code can help:

 <html>
    <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script>functionfunc(){varcidades=["Jaraguá do Sul", "Guaramirim", "Joinville" "Florianópolis"];
        var html = "";

    for(var i = 0; i < cidades.length; i++)
    {
        html =  '<option>'+cidades[i]+'</option>';
        document.getElementById('cidade').innerHTML += html;
    }
}

$('document').ready(function(){
func();
});
</script>
</head>
<body>
<label for="cidade">Cidade: <br>
        <select name="cidade" id="cidade" style="width:110px;">
                         <option value=""></option>
                        </select>                
                        </label>

<body>
</html>

Make sure your CSS class is not hiding the overflow of the select.

    
24.05.2018 / 14:55
1

First create the variable html with the <option> empty then go concatenating the for . Only after for , make innerHTML with all the already-formed string (it is recommended to insert HTML elements at one time than inserting inside the loop):

var html = '<option value=""></option>';
for(var i = 0; i < cidades.length; i++)
{
    html += '<option>'+cidades[i]+'</option>';
}
document.getElementById('cidade').innerHTML = html;
    
24.05.2018 / 15:05
0

Igor, if your function that compiles the list of options is in javascript, then change the function to the following form:

function func(){
    if(ajax.readyState == 4 && ajax.status == 200){
        eval(ajax.responseText);  

        if(dados.erro){
            alert(convertHtml(dados.erro));                    
        }else{
        var vazio = "";
        var cidades =  dados.split(",");
        var html = "";

       // Reiniciando a lista como vazia 
       document.getElementById('cidade').innerHTML = '<option></option>';

       for(var i = 0; i < cidades.length; i++)
       {
           html =  '<option>'+cidades[i]+'</option>';
           document.getElementById('cidade').innerHTML += html;
       }
    } 
}

You will enter the value and do not run the risk of the list growing with each re-updating of values. But I bring a suggestion to clean up some of your code ...

function func(){
    if(ajax.readyState == 4 && ajax.status == 200){
        eval(ajax.responseText);  

        if(dados.erro){
            alert(convertHtml(dados.erro));                    
        }else{
        var cidades =  dados.split(",");

       document.getElementById('cidade').innerHTML = getOption('');

       for(var i = 0; i < cidades.length; i++)
       {
           document.getElementById('cidade').innerHTML += getOption(cidades[i]);
       }
    }     
}

function getOption(value) {
    retunr '<option>'+ value + '</option>';
}

I hope I have helped you. Any other information will tell you that I edit the answer. Success!

    
24.05.2018 / 14:52