JavaScript change color problem - javascript

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)">

Related

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>
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.

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>

Form with input and output immediately reload the page after printing the output

I need to do a simple homework where you enter two integers in two text fields of a form and then you compute the sum and you print it in a "text field (not editable)". My program seems to work but it prints the right output and immediately reload the page. I want the page to remain with the printed output if the user does not click again on "submit" button
Here is my code HTML & JS :
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
}
<!DOCTYPE html>
<html>
<head>
<title>Number in a form</title>
<link href="mystyle.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="function.js">
</script>
</head>
<body>
<div id="mainDiv">
<H3>Insert two positive numbers</H3>
<form>
First number:<br>
<input id="n1" type="text" name="firstname"><br>
Second number:<br>
<input id="n2" type="text" name="lastname">
<BR>
<input type="submit" value="Submit" onClick="updateExpr()"/><BR><BR>
</form>
The sum is:<br>
<output id="sum" name="x" for="a b"></output>
</div>
<noscript>
Sorry: Your browser does not support or has disabled javascript
</noscript>
</body>
</html>
When form is submited, the page will be reloaded. To prevent this you should change input type attribute from submit to button.
<input type="submit" value="Submit" onClick="updateExpr()"/>
to
<input type="button" value="Submit" onClick="updateExpr()"/>
You can simply avoid server call by changing your form tag
<form onSubmit="return false">
You dont really need a form to do something like this.
Forms send values to the backend, e.g. a server.
You only want to manipulate some front-end elements like a container to have some new text inside it.
a <form> tag typically sends you to some URI with some aprameters,
this is done by the actions attribute.
<form action="addnames.php">
for example would call the addnames.php script on your server...
You dont need a server tho..look below:
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum =x1 +x2;
document.getElementById("sum").innerHTML = sum;
}
<h2>HTML Forms</h2>
First name:<br>
<input id="n1" type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input id="n2" type="text" name="lastname" value="Mouse">
<br><br>
<button type="submit" onclick="updateExpr()">Submit</button>
<div id="sum">
</div>
<script>
</script>
I would recommand you to add onSubmit method to the form instead of onclick to the input.
Also you better add a return : false to your function and add onsubmit="return updateExpr()".
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
return false;
}
<!DOCTYPE html>
<html>
<head>
<title>Number in a form</title>
<link href="mystyle.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="function.js">
</script>
</head>
<body>
<div id="mainDiv">
<H3>Insert two positive numbers</H3>
<form onsubmit="return updateExpr()">
First number:<br>
<input id="n1" type="text" name="firstname"><br>
Second number:<br>
<input id="n2" type="text" name="lastname">
<BR>
<input type="submit" value="Submit" onClick="updateExpr()"/><BR><BR>
</form>
The sum is:<br>
<output id="sum" name="x" for="a b"></output>
</div>
<noscript>
Sorry: Your browser does not support or has disabled javascript
</noscript>
</body>
Another way of doing this would have been to add a button outside of the form linked to the function by onclick event
juste add preventDefault(), like this
function updateExpr(e) {
e.preventDefault();
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
}

How to make a button for capitalization in JavaScript?

How can I change this script so that a user has to click a button at the end to make all form text entries change to capitals? I know that I need to use the onclick function, but I am just not sure where or how to enter it.
<html>
<head>
<title>Information Form</title>
<style>
input[type=text] {
text-transform: capitalize;
}
</style>
</head>
<body>
<input type="text" name="nameInput" />
Type your street address here:
<input type="text" address="addressInput" />
Type your city and state here:
<input type="text" cityandstate="stateInput" />
</body>
</html>
Something like this would work:
<html>
<head>
<title>Information Form</title>
<style>
input[type=text] {
text-transform: capitalize;
}
</style>
</head>
<body>
<input type="text" name="nameInput" />
Type your street address here:
<input type="text" address="addressInput" />
Type your city and state here:
<input type="text" cityandstate="stateInput" />
<div>
<button id="clickme" onclick="capInputs();">Capitalize Inputs</button>
</div>
<script>
function capInputs() {
var elements = document.querySelectorAll("input[type=text]")
for (var i = 0, element; element = elements[i++];) {
element.value = (element.value).toUpperCase();
}
}
</script>
</body>
</html>
See this :D
document.getElementById("myBtn").addEventListener("click", displayDate);
function displayDate() {
var x = document.getElementById("myBtn").innerHTML;
document.getElementById("myBtn").innerHTML =x.toUpperCase() ;
}
<html>
<body>
<p>This example uses the addEventListener() method to attach a click event to a button.</p>
<button id="myBtn">Try it</button>
</body>
</html>
You don't need to force the user to click a button at the end to change their text to uppercase. You can do this authomatically using JavaScript.
It looks like you've figured out that using CSS won't change the value of your inputs to uppercase, only change the appearance on the screen (and on my browser, text-transform doesn't even seem to work on the input element). Instead, you should attach event listeners to your the input event (which is fired every time input text is edited) inside a <script>...</script> tag (which should be inserted just before the closing </body> tag.
document.querySelectorAll('input').forEach(function(e) {
if (e.type === 'text') {
e.addEventListener('input', valueToUpperCase)
}
})
function valueToUpperCase(e) {
(e = e.target).value = e.value.toUpperCase()
}
<label>
Type your name here:
<input type="text" name="nameInput" />
</label>
<br/>
<label>
Type your street address here:
<input type="text" name="addressInput" />
</label>
<br/>
<label>
Type your city and state here:
<input type="text" name="stateInput" />
</label>
I am assuming (based on your css rule) that you want to capitalize the input text entries once the user press a button. If you want to change all text into upper case (i.e. all capital letters, not just the first one), then uppercase should be used in the css instead of capitalize.
#Amber Ollis, your code applies the CSS rule for capitalize to all input text elements from the beginning. The rule should only apply once pressed the button if that is the effect you want (I have added such button which is missing in your code).
See code below (working):
<html>
<head>
<title>Information Form</title>
<style>
.capitalized {
text-transform: capitalize;
}
</style>
<script>
function capitalize() {
var inputs = document.querySelectorAll("input[type=text]");
for (i in inputs) {
inputs[i].className = "capitalized";
}
}
</script>
</head>
<body>
<input type="text" name="nameInput" />
Type your street address here:
<input type="text" address="addressInput" />
Type your city and state here:
<input type="text" cityandstate="stateInput" />
<input type="button" onclick="capitalize();" value="Capitalize all" />
</body>
</html>

Create a "calculation form" in javascript

so I have a project now, as an addition to my company's website, we want to show our clients how much they can save on gas by buying one of our electric cars, I'm responsible for making it happen, I don't know how to approach this using javascript, can you guys give me a hand? our marketing guy got the idea from this website, that is basically what we want, but I was hoping i could make it a little better on some aspects:
1st-the client wouldn't have to press submit to see the results, as they fill the last field, the calculated part is populated automatically, for this i've been fiddling with the onChange event, unsuccessfully though xD
here's what I have so far, it is not working, at least on dreamweaver's live mode, haven't tested it online yet as I was hoping to develop the whole thing offline:
<script type="text/javascript">
function calc(){
var km=document.getElementById(km).value;
var euro=document.getElementById(euro).value;
var consumo=document.getElementById(consumo).value;
var cem_km=consumo*euro;
var fossil_day=(cem_km*km)/100;
return fossil_day;
}
</script>
<form name="calc" id="calc" >
<p>
Km/dia
<input type="text" name="km" id="km" value="" />
</p>
<p>
€/Litro
<input type="text" name="euro" id="euro" value="" />
</p>
<p>
Litros/100km
<input type="text" onChange="calc()" name="consumo" id="consumo" value="" />
</p>
<input type="button" onClick="calc()" name="submit" id="submit" value="Calcular" />
<script type="text/javascript">
var fossil_day = calc();
document.write('<p>'+fossil_day+'</p>');
</script>
</form>
Please note that although I have this already, I wouldnt mind not doing this at all and using another solution, even if it doesnt use forms, I'm just showing what i have already so you can tell me how I'm wrong and how I can have a better approach at it
there are many errors inside your code
document.getElementById() needs the element id in brackets ''
you can't create a element with the same name,id as a function calc else it will throw an error as it's an object and not a function.
your executing the function onload... but you want it to be executed when the button is clicked & onchange.
you don't need to add value if empty and name if you use getElementById
return false in the function on buttons inside form else it could send the form and so refresh the page.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>calc</title>
<script>
function calc(){
var km=document.getElementById('km').value;
var euro=document.getElementById('euro').value;
var consumo=document.getElementById('consumo').value;
var cem_km=consumo*euro;
var fossil_day=(cem_km*km)/100;
document.getElementById('result').innerHTML=fossil_day;
return false
}
</script>
</head>
<body>
<form>
<p>Km/dia<input type="text" id="km"/></p>
<p>€/Litro<input type="text" id="euro" /></p>
<p>Litros/100km<input type="text" onChange="calc()" id="consumo" /></p>
<input type="button" onClick="calc()" value="Calcular" />
</form>
<div id="result"></div>
</body>
</html>
Useing jQuery (and html5 type="number" form fields):
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form>
<p>
Km/dia
<input type="number" name="km" id="km" value="" />
</p>
<p>
€/Litro
<input type="number" name="euro" id="euro" value="" />
</p>
<p>
Litros/100km
<input type="number" name="consumo" id="consumo" value="" />
</p>
<div id="fossil-day"></div>
</form>
<script src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
<script>
function calculate(){
var km = $('#km').val();
var euro = $('#euro').val();
var consumo = $('#consumo').val();
var cem_km = consumo*euro;
var fossil_day = (cem_km*km)/100;
$('#fossil-day').html(fossil_day);
}
$(function() {
/*when #consumo input loses focus, as per original question*/
$('#consumo').blur(function(){
calculate();
});
});
</script>
</body>
</html>

Categories