Show what is selected from a select

4

How to display data in a <input> of JavaScript, according to what is selected from <select> ?

<script type="text/javascript">

function mostrarprecio() {
    if (document.getElementById('pizza').value = "0")
    {
        document.getElementById('precio').value = "0";
    }
    else if (document.getElementById('pizza').value == "1") {
        precio = "15000";
    }

}
</script>

<form>
    Seleccione la pizza:
    <select id="pizza" onchange="mostrarprecio()">
        <option value="0" id="0" ></option>
        <option value="15000" id="1">Queso</option>
        <option value="18000" id="2">Jamon</option>
        <option value="22000" id="3">Jamon y Queso</option>
        <option value="30000" id="4">Especial</option>
    </select>
    <input type="text" id="precio" />
    
asked by Juan Rodriguez 15.10.2016 в 20:48
source

3 answers

2

If what you want to show in the 'price' input is the price, you can do this:

function mostrarprecio() {
  var pizza = document.getElementById("pizza"),
     precio = document.getElementById("precio");

  precio.value = pizza.value;
}
<form>
  Seleccione la pizza:
  <select id="pizza" onchange="mostrarprecio()">
    <option value="0"></option>
    <option value="15000">Queso</option>
    <option value="18000">Jamon</option>
    <option value="22000">Jamon y Queso</option>
    <option value="30000">Especial</option>
  </select>
  <input type="text" id="precio" />
</form>
    
answered by 15.10.2016 в 22:00
0

You only need to modify your function with the following.

function mostrarprecio() {
    var pizzaSelect = document.getElementById("pizza");
    var optionSelected = pizzaSelect.options[pizzaSelect.selectedIndex].value;
    document.getElementById("precio").value = optionSelected;
}

Greetings.

    
answered by 15.10.2016 в 21:37
0

I can help you with jQuery, since it simplifies the amount of code.

$('select#pizza').change(function(){
  $('input').val($(this).val());  
});

And when you select, you can remove the onchange.

Regards, Christian

    
answered by 16.10.2016 в 00:06