Patryk Kobyłka
Patryk Kobyłka

Reputation: 69

how to call onClick button, a function from external JS file

I'm doing my first steps with JS and HTML, I'm trying to make a page for squaring a number, in the first box I enter a number, the second is blank, I click the button and I want the result of the number entered earlier to appear in the second box, the function is loaded from the external js file, can anyone explain how to do it?

HTML code

<html>

<head>
<title>Tytuł strony</title>
<link rel="stylesheet" href="styl.css" type="text/css" />

</head>

<body>
<section>
    <h2>Skrypt do potęgowania liczb</h2><br> 
Podaj liczbę którą podniesiemy do kwadratu:<br>
<input type="text" id="Liczba" value="" placeholder="Liczba" /><br>
<input type="text" id="Wynik" value="" placeholder="Wynik" /> 
<button type="button" id="Przycisk" onclick="Potegowanie(Liczba, Wynik)" >Oblicz</button><br>

</section>
<script type="text/javascript" src="script.js"></script>
</body>

</html>

JS code

<script type="text/javascript">
function Potegowanie(pole_na_liczbe, pole_na_wynik)
{
var liczba = document.getElementById("pole_na_liczbe").value;
var wynik = liczba*liczba;
pole_na_wynik.value = wynik;
}
</script>

Upvotes: 0

Views: 2257

Answers (1)

Paul Martin
Paul Martin

Reputation: 469

To get the first value, you could use the document.getElementById(); method, and reference the id of your first inout box, like...

var liczba = document.getElementById("Liczba").value;

...then after you've done the calculation, you could use a similar method to assign the value to your second input box...

document.getElementById("Wynik").value = wynik

Altogether, it looks like this...

   function Potegowanie()
        {
        var liczba = document.getElementById("Liczba").value;
        var wynik = liczba*liczba;
        document.getElementById("Wynik").value = wynik
        }
        <html>

        <head>
        <title>Tytuł strony</title>
        <link rel="stylesheet" href="styl.css" type="text/css" />
        <script type="text/javascript" src="script.js"></script>
        </head>

        <body>
        <section>
            <h2>Skrypt do potęgowania liczb</h2><br> 
        Podaj liczbę którą podniesiemy do kwadratu:<br>
        <input type="text" id="Liczba" value="" placeholder="Liczba" /><br>
        <input type="text" id="Wynik" value="" placeholder="Wynik" /> 
        <button type="button" id="Przycisk" onclick="Potegowanie()" >Oblicz</button><br>

        </section>
        
        </body>

        </html>

Extra pointer... In JavaScript, we use camelcase to name variables, id's and functions, so your function Potegowanie() for example would be better off being called potegowanie(). It will still work the same, but it's just good practice.

Upvotes: 2

Related Questions