Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda