Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
Naming function in JavaScript

As you can see in my code below, when I name my function discount(), the function does not run when it is called. However if I name it discounts(), it runs properly. Is there any explanation for this?

<html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>q3</title>
    </head>

    <body>
        <form action="">
            <label> Enter Price:</label>
            <input type="text" name="price" id="name">
            <label>(RM)</label><br><br>
            <label>Enter Discount:</label>
            <input type="text" name="discount" id="discount">
            <label>(%)</label><br><br>
            <button onclick="discount()">Get Discount total</button><br><br>
            <input type="text" name="discountPrice" id="discountPrice">
            <label>(RM)</label>
        </form>
        <script>
            function discount() {
                var price = document.getElementById("name").value;
                var discount = document.getElementById("discount").value;
                var discountPrice = parseFloat(price) * (1 - parseFloat(discount) / 100);
                document.getElementById("discountPrice").value = discountPrice;
            }
        </script>
    </body>

</html>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your code gives the following error:

TypeError: discount is not a function
    at HTMLButtonElement.onclick (/:14:34)

The reason for this is that you have the following line:

<input type="text" name="discount" id="discount"> 

So when you use onclick=discount(), the name discount here refers to the <input> element, not the discount() function. You need to use two distinct names for these to fix the problem.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda