Home > OS >  Html form input to variable for use in a js function
Html form input to variable for use in a js function

Time:09-02

<form onsubmit="calculos(); return false;">
 <label for="gasto">
        <span> Valor </span>
        <input
          required
          type="number"
          id="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

CodePudding user response:

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"
          
          name="gasto"
          placeholder="Valor.."
        />
      <input type="submit" value="submit"/>
</form>

  • Related