Fill a text from a select

0

I have a minimum code testing a java script in apache and it is not filling the text

<!DOCTYPE html>
<html>
<head>
<script text=javascript>
var select = document.getElementById('dropdown');
select.addEventListener('change', function(event) {
  var select = event.target;
  var indiceSeleccionado = select.selectedIndex;
  var elementoSeleccionado = select.options[indiceSeleccionado];
  var texto = document.getElementById('mytext');

  texto.value = select.value;

})
</script>
</head>
<input type="text" id="mytext">

<select id="dropdown" >

  <option value="">None</option>
  <option value="text1">text1</option>
  <option value="text2">text2</option>
  <option value="text3">text3</option>
  <option value="text4">text4</option>
</select>
</body>
</html>
    
asked by Maury Ferrera 23.08.2017 в 00:29
source

1 answer

0

You have to move the javascript to the end of the page to be able to achieve it:

<input type="text" id="mytext">

<select id="dropdown" >

  <option value="">None</option>
  <option value="text1">text1</option>
  <option value="text2">text2</option>
  <option value="text3">text3</option>
  <option value="text4">text4</option>
</select>

<script text=javascript>
var select = document.getElementById('dropdown');
select.addEventListener('change', function(event) {
  var select = event.target;
  var indiceSeleccionado = select.selectedIndex;
  var elementoSeleccionado = select.options[indiceSeleccionado];
  var texto = document.getElementById('mytext');

  texto.value = select.value;

})
</script>

The code execution of the page is executed in waterfall mode, starting from the top to the end of the page. In your code var select = document.getElementById('dropdown'); is executed before the select itself has even been rendered and therefore can not find it.

    
answered by 23.08.2017 в 01:45