Repeat selected data in a select in a text input

Asked

Viewed 176 times

0

How to repeat the selected values in one select in a input[type="text"] bearing in mind 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">

2 answers

2


You can do it like this (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 Javascript above for:

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

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

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

1

Using jQuery you can assign a method to the event change in select so that when the user changes the selected option the method updates the value of input text just 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>

Browser other questions tagged

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