Error in alert, javascript and html does not appear at alert

-2

function btn() {

  window.location.href = "index.html";
  var precioP = document.getElementById('precioP').value;
  var nombreP = document.getElementById('nombreP').value;



  if (precioP == "" || nombreP == "") {
    alert("achu, los datos son obligatorios achu!");
    return false;
  }


}
<div class="index">
  <form action="alta.php" method="GET">
    <FIELDSET>
      <center>
        <LEGEND><b>Alta producto</b></LEGEND>
        <hr><br><br>
        <label>Nombre del producto</label><br><br>
        <input type="text" name="nombreP" id="nombreP"><br><br>
        <label>Precio producto</label><br><br>
        <input type="number" step="0.01" name="precioP" id="precioP"><br><br>
        <button style="width:50%" id="btn" onclick="btn()">GUARDAR DATOS</button>
      </center>
    </FIELDSET>
  </form>
</div>

When I run it and I do not write anything, I do not get the alert, it's as if they have not connected properly.

    
asked by ally_ pretty 13.05.2018 в 07:46
source

2 answers

0

You have to put the JavaScript code inside the script tag

<script>
    function btn() {

        window.location.href="index.html"; 
        var precioP=document.getElementById('precioP').value;
        var nombreP=document.getElementById('nombreP').value;

        if (precioP=="" || nombreP=="") {
            alert ("achu, los datos son obligatorios achu!");
            return false;
       }
   }
</script>
    
answered by 14.05.2018 в 21:00
0

Your problem is that there is a conflict with names, in doing this

<button style="width:50%" id="btn" onclick="btn()">GUARDAR DATOS</button>

The id and the function have the same name and this may cause conflicts in some browsers, change the name of id or function.

I added the type=button so you do not send the form automatically

function btnFunc() {
  var precioP = document.getElementById('precioP').value;
  var nombreP = document.getElementById('nombreP').value;
  if (precioP == "" || nombreP == "") {
    alert("achu, los datos son obligatorios achu!");
  } else {
    document.getElementsByTagName('form')[0].submit();
  }
}
<div class="index">
  <form action="alta.php" method="GET">
    <FIELDSET>
      <center>
        <LEGEND><b>Alta producto</b></LEGEND>
        <hr><br><br>
        <label>Nombre del producto</label><br><br>
        <input type="text" name="nombreP" id="nombreP"><br><br>
        <label>Precio producto</label><br><br>
        <input type="number" step="0.01" name="precioP" id="precioP"><br><br>
        <button type="button" style="width:50%" id="btn" onclick="btnFunc()">GUARDAR DATOS</button>
      </center>
    </FIELDSET>
  </form>
    
answered by 14.05.2018 в 22:19