How do I leave an option like "default" on a combobox?

Asked

Viewed 225 times

1

I have a combobox with several "values". I will "fail" values, just for example. Combobox:

<ul class="nav">
   <li>
      <div>
         <label>Tipo de Nacionalidade</label>
         <select id="comboTipoId" style="max-width: 350px; width: 350px; background-color: #eee; overflow: hidden; max-height: 37px; height: 37px">

         </select>
      </div>
   </li>
</ul>   

Function JS that fills this combo (call this Function in the "onload" page):

function preencherCampos() {       

   /* Busca em arquivo o preenchimento do combobox "Tipo Nacionalidade" */
   /* 'Chumbando' JSON... */
   var consultaTipoId = '{ "tab" : "00000007", "descr" : "Tipo da Nacionalidade", "itens" : [{ "seq" : "1", "value" : "NACIONALIDADE - PF", "key" : "1" }, { "seq" : "2", "value" : "RESIDENCIA FISCAL - PF/PJ", "key" : "2" }, { "seq" : "3", "value" : "VISTO DE PERMANENCIA - PF", "key" : "4" }, { "seq" : "4", "value" : "PAIS DE CONSTITUICAO - PJ", "key" : "5" }, { "seq" : "5", "value" : "PAIS DE NASCIMENTO - PF", "key" : "9" }] }';
   var jsonRespostaCTI = JSON.parse( consultaTipoId );
   for(var i = 0; i < jsonRespostaCTI.itens.length; i++) {
      // get reference to select element
      var sel = document.getElementById('comboTipoId');

      // create new option element
      var opt = document.createElement('option');

      // create text node to add to option element (opt)
      opt.appendChild( document.createTextNode(jsonRespostaCTI.itens[i].value) );

      // set value property of opt
      opt.value = jsonRespostaCTI.itens[i].key;

      // add opt to end of select box (sel)
      sel.appendChild(opt);
   }
   ordenarTpNac();
}

Function JS to sort combo alphabetically:

function ordenarTpNac() {
   var itensOrdenados = $('#comboTipoId option').sort(function (a, b) {
      return a.text < b.text ? -1 : 1;
   });

   $('#comboTipoId').html(itensOrdenados);
}

The problem is that, after sorting, the "default" value that appears to the user is "VISA OF PERMANENCE - PF" (the last value). I wanted it to be "default" to "PARENTS OF BIRTH - PF" (key "9"). How to do this? I tried to put something like if(opt.value == "9") { opt.setected = "Selected"; } inside the function’s end fill fields() but it didn’t work...

1 answer

1


Before making the append of options, put a if to insert the attribute selected option whose value is 9:

if(jsonRespostaCTI.itens[i].key == 9) opt.setAttribute("selected", "");

Will result in HTML:

<option value="9" selected>PAIS DE NASCIMENTO - PF</option>

Behold:

function preencherCampos() {       

   /* Busca em arquivo o preenchimento do combobox "Tipo Nacionalidade" */
   /* 'Chumbando' JSON... */
   var consultaTipoId = '{ "tab" : "00000007", "descr" : "Tipo da Nacionalidade", "itens" : [{ "seq" : "1", "value" : "NACIONALIDADE - PF", "key" : "1" }, { "seq" : "2", "value" : "RESIDENCIA FISCAL - PF/PJ", "key" : "2" }, { "seq" : "3", "value" : "VISTO DE PERMANENCIA - PF", "key" : "4" }, { "seq" : "4", "value" : "PAIS DE CONSTITUICAO - PJ", "key" : "5" }, { "seq" : "5", "value" : "PAIS DE NASCIMENTO - PF", "key" : "9" }] }';
   var jsonRespostaCTI = JSON.parse( consultaTipoId );
   for(var i = 0; i < jsonRespostaCTI.itens.length; i++) {
      // get reference to select element
      var sel = document.getElementById('comboTipoId');

      // create new option element
      var opt = document.createElement('option');

      // create text node to add to option element (opt)
      opt.appendChild( document.createTextNode(jsonRespostaCTI.itens[i].value) );

      // set value property of opt
      opt.value = jsonRespostaCTI.itens[i].key;
      
      if(jsonRespostaCTI.itens[i].key == 9) opt.setAttribute("selected", "");

      // add opt to end of select box (sel)
      sel.appendChild(opt);
   }
   ordenarTpNac();
}

function ordenarTpNac() {
   var itensOrdenados = $('#comboTipoId option').sort(function (a, b) {
      return a.text < b.text ? -1 : 1;
   });

   $('#comboTipoId').html(itensOrdenados);
}
preencherCampos()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="nav">
   <li>
      <div>
         <label>Tipo de Nacionalidade</label>
         <select id="comboTipoId" style="max-width: 350px; width: 350px; background-color: #eee; overflow: hidden; max-height: 37px; height: 37px">

         </select>
      </div>
   </li>
</ul>

  • So, dude, the problem with this solution is that, after the end of the function fillCampos(), the function orderTpNac() executed then "mess" the default choice. I saw that in your example, you called the function fill Fields() below the ordering TpNac() and, for some reason that I didn’t understand, it worked in your example, but with me, the page broke because it was in infinite loop. There is no way I can choose the default within the sort function (which is executed "last")?

  • 1

    See, the fact of making an ordering does not change the option that is selected, it will remain selected.

  • You’re right, man, it’s just that I was trying to implement that same change on another combobox and it didn’t work. I think it’s because JSON is different, and then I have to change something in logic; you can help me see what it is?

  • I will post in a new comment, otherwise, exceeds the limit of characters... Hehe

  • var novoJSON = '{ "tab" : "00000004", "descr" : "Parents", "items" : [ { "seq" : "45", "value" : "BOTSWANA", "key" : "045", "ufs" : [] }, { "seq" : "46", "value" : "BRASIL", "key" : "046", "ufs" : [ { "seq" : "1", "value" : "RONDONIA", "Abrev" : "RO", "key" : "000010", "doc" : [ { "seq" : "1", "value" : "GENERAL RECORD WITHOUT CPF", "key" : "00007", "emissao" : "S", "venc" : "N value"Exp" [ { "seq" : "1", """"""" : "DIRECTORATE CIVIL IDENTIFICATION", "key" : "DIC " } ] ], "municipios" : [ { "seq" : "1", "value" : "ARIQUEMES", "key" : "0000009393" } ] } ] } ] }';

  • this new JSON, when I parse and run it, even putting the if you put, does not work (I wanted Brazil to be visible to the user, key "046"). The country is selected in the application (I have already tested), but what appears to the user is the last ordered country of the JSON (the last item of the "bracket" "items"). Remembering that I only put part of this new JSON here (the minimum to be "intelligible", at least), because it is very large... It has all the countries of the world, plus the states and municipalities of Brazil, with agencies issuing documents, would be impossible to post the whole JSON.

  • These JSON’s you pulling how? Is it in PHP, AJAX? I think there’s a better way to choose the default option.

  • So, I pull a function. This function is in an Android app. It’s just that I’m actually doing just the front of this Android app. Then, one of the requirements is this: leave the country Brazil as "default" for the user to facilitate the completion of the form.

  • 1

    I think it would be better, after the popular select, to do: $("#comboTipoId option[value='9']").attr("selected", "");

  • 1

    Gee, man, that worked, I played this piece of code in the function that orders, right after she finished ordering and it worked!!! : ) Rigadão!

Show 5 more comments

Browser other questions tagged

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