How to change the select text after an option is chosen?

3

I'm making an application where the user should select their ddi . ddi is in select as follows:

<select name="paises" id="ddi">
     <option value="55" id="bra">Brasil</option>
     <option value="1" id="eua">Eua</option>
</select>

I've put two lines, just one example, several. I would like that when the user selects the country, for example, Brazil , what appears after selected is 55 and not% Brazil . I hope I can explain.

    
asked by anonymous 28.12.2016 / 13:14

2 answers

2

You can do this:

ddi.onchange = function() {
  var option = this.querySelector('option:checked');
  option.setAttribute('data-name', option.innerHTML); //essa parte é opcional caso você não queira voltar com os nomes
  option.innerHTML = option.value;
  
  // Voltar com o valor original dos outros campos (essa parte é opcional caso você não queira voltar com os nomes)
  this.querySelectorAll('option:not(:checked)').forEach(function(option) {
      var name = option.getAttribute('data-name');
      if(name) option.innerHTML = name;
  });
  //
}
<select name="paises" id="ddi">
  <option value="" disabled selected>Selecione</option>
  <option value="55">Brasil</option>
  <option value="1">Eua</option>
</select>

2nd Form (suggested by @TiagoGomes)

ddi.onchange = function() {
  var selectedOption = this.querySelector('option:checked');
  
  displayValue.innerHTML = selectedOption.value;
  displayValue.value = selectedOption.value;
  this.value = selectedOption.value;
}
<select name="paises" id="ddi">
  <option id="displayValue" value="" selected disabled>Selecione</option>
  <option value="55">Brasil</option>
  <option value="1">Eua</option>
</select>

OBS1: I do not think this is the best solution for your problem, but for the way you described it, it will help.

OBS2: I think the way that @LucasCosta mentioned in the comment gets better!

    
28.12.2016 / 13:39
2

I do not know if I understood your demand exactly, but here is a functional example and jQuery.

// id do select
var objeto = $("#ddi");

// salva o texto atual para poder ser recuperado
$.each($(objeto).children('option'), function(){
  console.log($(this).text());
  $(this).attr('des', $(this).text());
});
$("#ddi option:selected").text('+' + $('#ddi').val()); // marca o selecionado


// ao mudar a seleção (pode ser ao perder o foco ou da forma que preferir)
$('#ddi').change(function(){
  $("#ddi option").text($("#ddi option").attr('des'));
  $("#ddi option:selected").text('+' + $('#ddi').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectname="paises" id="ddi">
         <option value="55"  id="bra">Brasil</option>
         <option value="1"  id="eua">Eua</option>
</select>
    
28.12.2016 / 13:47