Un problema que tienes es que text
no está definido.
Antes del switch
se inicializa. Yo le puse un texto en caso de que no entre en ningun case
del switch
.
Otro problema es que envia la información del form
(en jsfiddle se quejaba de que no ponía method="POST"
) porque el tag <button>
hace submit del formulario.
Asi que cambié el <button>
por un <input type="button">
y ya funciona.
function province() {
var zipcode = document.getElementById("zipcode");
var zip = zipcode.value;
var text = "not found";
switch (zip.substring(0, 2)) {
case "01":
text = "Álava";
break;
case "02":
text = "Albacete";
break;
case "03":
text = "Alicante";
break;
}
document.getElementById("zipcode2").innerHTML = text;
}
<html>
<head>
</head>
<body>
<form>
<input type="number" id="zipcode"><input type="button" id="localize" onclick="province()" value="Localize"><br/>
</form>
<p id="zipcode2"></p>
<script src="3.js"></script>
</body>
</html>
Otra solución habría sido pasar el evento a province( event )
y luego en el método usar event.preventDefault()
para evitar que haga el submit
del formulario.
function province(e) {
var zipcode = document.getElementById("zipcode");
var zip = zipcode.value;
var text = "not found";
switch (zip.substring(0, 2)) {
case "01":
text = "Álava";
break;
case "02":
text = "Albacete";
break;
case "03":
text = "Alicante";
break;
}
document.getElementById("zipcode2").innerHTML = text;
e.preventDefault();
}
<html>
<head>
</head>
<body>
<form>
<input type="number" id="zipcode"><button id="localize" onclick="province(event)">Localize</button><br/>
</form>
<p id="zipcode2"></p>
<script src="3.js"></script>
</body>
</html>
O poner el evento onsubmit="return false;"
en el <form>
.
function province() {
var zipcode = document.getElementById("zipcode");
var zip = zipcode.value;
var text = "not found";
switch (zip.substring(0, 2)) {
case "01":
text = "Álava";
break;
case "02":
text = "Albacete";
break;
case "03":
text = "Alicante";
break;
}
document.getElementById("zipcode2").innerHTML = text;
}
<html>
<head>
</head>
<body>
<form onsubmit="return false;">
<input type="number" id="zipcode"><button id="localize" onclick="province()">Localize</button><br/>
</form>
<p id="zipcode2"></p>
<script src="3.js"></script>
</body>
</html>
(Gracias @OscarGarcia por tu comentario)