Repeat selected data in a select in a text input

0

How do I repeat the selected values in a select in a input[type="text"] considering my HTML below using JavaScript?

<select name="destino_in" class="form-control" required>
  <option value="Vilamar">Vilamar</option>
  <option value="Savoy">Savoy</option>
</select>

<!-- dados a serem repetidos aqui -->
<input type="text" name"destino_out">
    
asked by anonymous 10.01.2018 / 18:00

2 answers

2

You can do this like without jQuery ):

(function () {
  var sel = document.getElementById('destino_in');
  var inp = document.getElementById('destino_out');

  sel.addEventListener('change', function () {
    inp.value = this.value;
  });
}());
<select name="destino_in" id="destino_in" class="form-control">
  <option value="" selected disabled>Selecione...</option>
  <option value="Vilamar">Vilamar</option>
  <option value="Savoy">Savoy</option>
</select>

<input type="text" name"destino_out" id="destino_out" "form-control" />

If you want to use jQuery, just change the above JavaScript to:

(function ($) {
  $('#destino_in').on('change', function () {
    var $self = $(this);

    $('#destino_out').val($self.val());
  });
}(jQuery));
  

However, always prefer not to use jQuery, since you do not need to load the library to do trivial effects like this.

    
10.01.2018 / 18:19
1

Using jQuery you can assign a method to the change event in the select so that when the user changes the selected option the method updates the input text value directly below.

<form action="#">
  <select id="lista" name="destino_in" on-change="atualizar()">
    <option value='Vilamar'>Vilamar</option>
    <option value='Savoy'>Savoy</option>
  </select>
  <input type="text" id="selecionada" name="destino_out">
</form>
<script>
  $(function () {
    function update() {
      $("#selecionada").val($("#lista").val());
    }
    update();
    $( "#lista" ).change(update);
  });
</script>
    
10.01.2018 / 18:25