Pablo Barrios Pablo Barrios - 2 months ago 8
HTML Question

Javascript Issue changing a form input

Thanks in advance.

I want to change the value of input text "total" in a form depending the value of the select "opciones". I tried with

onchange()
, with
document.getElementById("")
.value but it doesn't works.

I dont know what is failing, but I cannot change the input value.

<form name="formulario">

<select name="opciones" id="opciones">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<input type="text" name="suma" id="total">
</form>


Javascript:

function formtotal() {

if (document.formulario.opciones.value = "1") {

document.formulario.suma.value = "1000";
}

else if (document.formulario.opciones.value = "2") {

document.formulario.suma.value = "1250";
}

else if (document.formulario.opciones.value = "3") {

document.formulario.suma.value = "1500";
}

}

Answer

I think instead of document.formulario.suma.value it should be document.formulario.total.value.

However, below code is working fine. Tested in jsfiddle (link below).

function formtotal() {
    var x = document.getElementById("opciones").value;
    if (x == "1") {
        document.getElementById("total").value = "1000";
    }
    else if (x == "2") {
        document.getElementById("total").value = "1250";
    }
    else if (x == "3") {
        document.getElementById("total").value = "1500";
    }
}

Add onchange to the select tag as per below snippet:

<select name="opciones" id="opciones" onchange="formtotal()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

https://jsfiddle.net/fghxhtmk/ - Working fine. Please check.

EDIT: Added "value" to each option tag.