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

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>

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.

Related

ReferenceError: Can't find variable X when calling JS function (or variable) from HTML file

I am trying to call a function in an external JavaScript file from an HTML-file. The goal is to work with the content of a form there.
I tried so many things and always got the Error "ReferenceError: Can't find variable: X"
The positioning of the jquery javascript file loading
The positioning of the <script src="XXX"> call
Calling the function from the button "onclick" or the form "onsubmit"
Trying to call the javascript file from an embedded script in the HTML
This is what my JavaScript file and my HTML looks like right now:
function submit(e) {
answerText = document.getElementById("text").value;
// Do something with it.
}
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="/scripts/debug_alerts.js" type="text/javascript"></script>
</head>
<body>
<form id="validation-form" onsubmit="return submit(e)">
<input type="text" class="form-control" name="text" id="text" placeholder="Text" required>
<button type="button" class="btn btn-primary" onclick="submit(e)">Send</button>
</form>
</body>
I also tried
function doSomething() {
// Do something
}
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="/scripts/debug_alerts.js" type="text/javascript"></script>
</head>
<body>
<form id="validation-form" onsubmit="return submit(e)">
<input type="text" class="form-control" name="text" id="text" placeholder="Text" required>
<button type="button" class="btn btn-primary" onclick="submit(e)">Send</button>
</form>
<script>
function submit(e) {
doSomething();
}
</script>
</body>
In both cases, it returned the same error over and over again: "ReferenceError: Can't find variable: X". In the first example, X being "submit" and in the second "doSomething".
All help is very welcome. I know there are similar headlines here, but non of the solutions did anything for me.
Hey so when I ran the code without the e as a parameter for the submit function in the html it didn't give me the error. I think it may be because the e is the place holder for the text of the submit function in this case. Hope this helps.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="/scripts/debug_alerts.js" type="text/javascript"></script>
</head>
<body>
<form id="validation-form" onsubmit="return submit(e)">
<input type="text" class="form-control" name="text" id="text" placeholder="Text" required>
<button type="button" class="btn btn-primary" onclick="submit()">Send</button>
</form>
<script type="text/javascript">
function submit(e) {
answerText = document.getElementById("text").value;
// Do something with it.
}
</script>
</body>
</html>

How do I trigger a JavaScript function when a button is pressed in HTML code

I am trying to create a calculator that solves the Pythagoras theorem. I have created a function inside a tag in my code which takes two arguments (one for each leg length of the right-angled triangle) The function works if I just do a console.log with two numbers as arguments and the function executes properly if it is inside the script tag. But I just want to know how to take the two arguments in the text boxes and then when I press the button make the result appear on the screen.
<html>
<main>
<head>
<!--Textboxes to input lengths of legs-->
<input type = "text" required placeholder= "1st legnth">
<br> <br>
<input type = "text" required placeholder= "2nd legnth">
<br> <br>
<button type = "submit">Give me the answer.
</head>
</main>
</html>
<script>
function solveforHyp (a, b)
{
var c = a*a + b*b;
return Math.sqrt(c);
}
var final = (solveforHyp(3, 4));
console.log(final);
</script>
add a span after the button to contain the final result:
<span id="final-result"></span>
add an onclick event to your button, it might look like this:
<button type="button" onclick="onButtonSubmit()"></button>
you might also give some relevant ID's to the input like this:
<input type = "text" id="first-length" required placeholder= "1st legnth">
<input type = "text" id="second-length" required placeholder= "2nd legnth">
and finally, write the onButtonSubmit function to access the inputs and call the solveforHyp function :
function onButtonSubmit(){
const firstValue = document.getElementById('first-length').value;
const secondValue = document.getElementById('second-length').value;
document.getElementById('final-result').innerText = solveforHyp(firstValue,secondValue); // finally, put the returned value in the created span.
}
First of all your document structure is entirely wrong, a lot of tags are not closed script is after the HTML tag, and content is written inside head tag and head is inside main, NO doctype declaration is done, and most importantly if you wanna submit something you should have a form at least with preventing its default behavior. Learn HTML before JavaScript Brother, and also its a good practice to use input type Number when you already know the input will be always a Number.
and here is the code what you are trying to make
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<form id="formOne">
<input type="number" required placeholder="1st legnth" id="first">
<br> <br>
<input type="number" required placeholder="2nd legnth" id="second">
<br> <br>
<button type="submit">Give me the answer</button>
</form>
</body>
<script>
let form = document.querySelector("#formOne");
let inputOne = document.querySelector("#first");
let inputTwo = document.querySelector("#second");
form.addEventListener("submit", function(e){
e.preventDefault();
console.log(Math.sqrt(Math.pow(inputOne.value,2) + Math.pow(inputTwo.value,2)));
})
</script>
</html>
Js file function to be called
function tryMe(arg) {
document.write(arg);
}
HTML FILE
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src='object.js'> </script>
<title>abc</title><meta charset="utf-8"/>
</head>
<body>
<script>
tryMe('This is me vishal bhasin signing in');
</script>
</body>
</html>
You can try like this:
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<form id="form">
<input type="text" id="first_length" name="first_length" />
<input type="text" id="second_length" name="second_length" />
<input type="submit" value="Submit" />
</form>
<script>
function logSubmit(event) {
event.preventDefault();
var first_length = document.getElementById("first_length").value;
var second_length = document.getElementById("second_length").value;
var final = solveforHyp(first_length, second_length);
console.log(final);
}
const form = document.getElementById("form");
form.addEventListener("submit", logSubmit);
function solveforHyp(a, b) {
var c = a * a + b * b;
return Math.sqrt(c);
}
</script>
</body>
</html>

Send JavaScript variable to HTML page

I have the following HTML page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>demo</title>
<link rel="stylesheet" href="style.css" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="field">
<label for="value1">Introduce value</label>
<input type="text" id="value1" name="value1" value="" />
</div>
<div class="button-block">
<input type="submit" value="Click" />
</div>
<div id="output">
<h2>Result:</h2>
<textarea name="result" id="result"></textarea>
</div>
</body>
</html>
I want to get the value that is introduced in value1 and when the submit is clicked to put that value in the output. So I wrote in script.js the following code but somehow it doesn't work.
<script>
window.onload = function(){
var val = document.getElementById('value1').innerHTML;
document.getElementById('result').innerHTML = val;
};
</script>
Any ideas?
You have to use .value property of the input field instead of innerHTML. so it would be:
var val = document.getElementById('value1').value;
and also, since you're executing it when the page loads. There will be no value assigned to the input field with id 'value1'. Therefore, you won't get any result.
You can try adding a button with onClick event to execute this function in place of using window.onload
HTML controls you are working on are textboxes, so they have a value property, not innerHTML.
Use this:
var val = document.getElementById('value1').value;
document.getElementById('result').value= val;
You can't get the value of an input element using the innerHTML attribute. Use value instead:
var val = documento.getElementById('value1').value;
Also you should keep in mind that your function is executed when the page loads, NOT when the form is submitted.
The code is not working, because you are calling this function when the window loads, not when the submit button is clicked. Since there is no form, and thus no page loading going on, I'd recommend switching the <input type="submit" value="Click" /> to a button. They are functionally similar, and visually identical. With the the button, though you could use the onclick attribute to call a function when the button is clicked. See below for an example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>demo</title>
<link rel="stylesheet" href="style.css" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="field">
<label for="value1">Introduce value</label>
<input type="text" id="value1" name="value1" value="" />
</div>
<div class="button-block">
<button onclick="printOutput()">Click</button>
</div>
<div id="output">
<h2>Result:</h2>
<textarea name="result" id="result"></textarea>
</div>
</body>
</html>
Then in your script.js you would have,
function printOutput(){
var val = document.getElementById('value1').value;
document.getElementById('result').innerHTML = val;
}
when the submit is clicked to put that value in the output
You have chosen wrong event window.onload, also you need .value instead of .innerHTML
Option 1: using jQuery, as you already have the import
$(function() {
$('input[type="submit"]').on('click', function(e) {
$('#result').val($('#value1').val());
});
});
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<div class="field">
<label for="value1">Introduce value</label>
<input type="text" id="value1" name="value1" value="" />
</div>
<div class="button-block">
<input type="submit" value="Click" />
</div>
<div id="output">
<h2>Result:</h2>
<textarea name="result" id="result"></textarea>
</div>
Option 2: using plain js
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelector('input[type="submit"]').addEventListener('click', function(e) {
document.querySelector('#result').value = document.querySelector('#value1').value;
});
});
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<div class="field">
<label for="value1">Introduce value</label>
<input type="text" id="value1" name="value1" value="" />
</div>
<div class="button-block">
<input type="submit" value="Click" />
</div>
<div id="output">
<h2>Result:</h2>
<textarea name="result" id="result"></textarea>
</div>
<script>
$( document ).ready(function() {
setTimeout(function(){
var val = document.getElementById('value1').innerHTML;
var generateHere = document.getElementById("result");
generateHere.innerHTML = val;
}, 2000);
});
</script>

passing variable to javascript function and using it in document.form?

<!DOCTYPE html>
<html>
<head>
<title>Database test</title>
<link rel="stylesheet" type="text/css" href="test.css">
<script>
function validateForm(n)
{
var x=document.forms.SignUp.n.value;
alert("*"+x+"*");
}
</script>
</head>
<body>
<h1>Just a Database test</h1>
<form name="SignUp" action="http://127.0.0.1/cgi-bin/connectivity.cgi" onsubmit="return validateForm();" method="post">
Ename :<input type="text" name="ename" onchange="validateForm('ename');"><br><p id="error_1"></p>
<input type="submit" value="Send">
</form>
</body>
</html>
I am trying to pass the user input value by onchange="validateForm('ename') but it does not seem to work i dont get anything.
instead if i change function to this then it works but again i need to pass it as varaible from onchange="validateForm('ename').
function validateForm(n)
{
alert("*"+n+"*");
}
You should pass the element itself, which is this inside an inline handler:
validateForm(this);
function validateForm(elem)
alert(elem.value);
}
One way to make it work, without changing your function call:
function validateForm(n) {
var x = document.forms.SignUp[n].value;
alert("*"+x+"*");
}

JavaScript change color problem

I've seen all the posts but my problem isn't that it doesn't change the background color but rather that it does and the change it but to the original. Here's the code.
<html>
<head>
<title>Calculator</title>
<link rel="stylesheet" type="text/css" href="color.css"/>
<script type="text/javascript">
function calc(color){
//document.body.bgColor = color;
x=document.myForm
var val1=x.input1.value;
var val2=x.input2.value;
var val3=val1+"+"+val2;
if(eval(val3)<0) return;
else{
alert("The result is "+eval(val3));
var bd = document.getElementById ('body');
bd.className="highlight";
return;
}
}
</script>
</head>
<body id="body" onload="changeBackground(red)">
<form name="myForm" onsubmit="calc(this)">
Enter 2 values to add ;)
<input type="text" name="input1">
<input type="text" name="input2">
<input type="submit" value="Send Input">
</form>
</body>
</html>
CSS:
.hightlight{
background-color: yellow;
}
I understand that the function ends right before the end of the function. So how can I get it to hold the color?
The problem is that you tries to POST page over submit button. In this case page is fully redrawn, without keeping previous state that is set by your script.
Just change code of button:
<input type="button" value="Send Input" onclick="calc(this)">

Categories