简体   繁体   中英

Html form input to variable for use in a js function

<form onsubmit="calculos(); return false;">
 <label for="gasto">
        <span> Valor </span>
        <input
          required
          type="number"
          id="gasto"
          class="gasto"
          name="gasto"
          placeholder="Valor.."
        />
      </label>
      <input type="submit" value="submit"/>
</form>

script trying to take that input into a variable for a function to return that inpunt and * to print in web

<script language="javascript">

      function calculos() {
        document.getElementById("gasto").value;
        var num1 = document.getElementById("gasto").value;
        Honorarios = num1 * 0.3;
        Escribania = num1 * 0.2;
        sellos = num1 * 0.05;
        return (Honorarios, Escribania, sellos);
        console.log(gasto);
        console.log(Honorarios);
        console.log(Escribania);
        console.log(sellos);
        alert(gasto, Honorarios, Escribania, sellos);
      }
      calculos();
    </script>

sorry if i dont explain good enough im learing html and js and wanted to make a calculator that you input a amount and the algorithm gives you back that amount * by 0.05 and others thanks

I edited your code, and removed the unnecessary lines, also moved the label HTML element which was badly placed, it works now, watch out for console log. I also combined all results into a single string before alert line.

 function calculos() { document.getElementById("gasto").value; var num1 = document.getElementById("gasto").value; Honorarios = num1 * 0.3; Escribania = num1 * 0.2; sellos = num1 * 0.05; console.log(Honorarios); console.log(Escribania); console.log(sellos); let allOfThem = `Honorarios: ${Honorarios} Escribania: ${Escribania} sellos: ${sellos}` alert(allOfThem); } //calculos(); This function SHOULD never be here, as it will be called everytime.
 <form onsubmit="calculos(); return false;"> <label for="gasto"> <span> Valor </span> </label> <,-- This was moved here to the right place. it was at the end of form --> <input required type="number" id="gasto" class="gasto" name="gasto" placeholder="Valor.." /> <input type="submit" value="submit"/> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM