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

Asked

Viewed 1,373 times

0

I have a select of cities that is supplied dynamically with the query returned in the databases, but when the values in the option the default value emptiness some preventing to select an empty row. Look at:

Select emptiness: inserir a descrição da imagem aqui

Select stocked:

inserir a descrição da imagem aqui

Follow codes who supply the options:

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 = "";

    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>
  • What is the code that calls this function? It seems to have some other code that manipulates the select

  • @Gabrielheming he is calling an Onchange event of the UF select to be able to consult at the bank and return the cities.

4 answers

1

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

 <html>
    <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>

function func() {
        var cidades = ["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>

Print de como ficou

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

1


Just create a option with empty text and add to the end of for in the 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, the option could be added simply like this:

select.add(opt);

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

1

First create the variable html with the <option> empty then concatenate into the for. Just after the for, do the innerHTML with all the string already formed (it is recommended to insert HTML elements at once than go 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;

0

Igor, if your function setting up the list of options is in javascript, so 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 not run the risk of the list growing with each re-visualization of values. But I have a suggestion to clear up your code a little bit...

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!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.