JavaScript - result disappears immediately [duplicate] - javascript

This question already has answers here:
JavaScript code to stop form submission
(14 answers)
Closed 4 years ago.
I am a beginner to JavaScript. I am buliding a BMI calculator. It gives the output for a few milliseconds and then the result disappears.
<!DOCTYPE html>
<html>
<head>
<title>BMI Calculator</title>
</head>
<body>
<form>
Weight:-<input type="text" id="wtxt"><br>
Height:-<input type="text" id="htxt"><br>
BMI:-<input type="text" id="bmitxt"><br>
<input type="reset" value="clear"><br>
<button onclick="calcbmi()">Calc BMI</button>
</form>
<script type="text/javascript">
function calcbmi(){
var w=parseInt(document.getElementById('wtxt').value);
var h=parseInt(document.getElementById('htxt').value);
var z=w/(h*h);
document.getElementById('bmitxt').value=z;
}
</script>
</body>
</html>

To separate behavior from the view, you can do it like this:
The button:
<button>Calc BMI</button>
The script:
<script type="text/javascript">
document.querySelector("button").addEventListener("click", function(event) {
calcbmi();
event.preventDefault();
}, false);
function calcbmi() {
var w = parseInt(document.getElementById('wtxt').value);
var h = parseInt(document.getElementById('htxt').value);
var z = w / (h * h);
document.getElementById('bmitxt').value = z;
}
</script>
Source

Looks like the comments are answering your question. Shortest path is to change the button to a different type so it doesn't submit the form, thus causing the page to load again. Form makes it simple for inputs, but isn't strictly necessary.
Calc BMI
More info here:
How to prevent buttons from submitting forms

By default, form makes a GET request on submit. Source
You're submitting the form each time you click submit and the browser is trying to make a request to nothing since there is no action attribute specified. I've copied a working example of your code below. As noted in the comments, remove the form. Your code will work then.
<!DOCTYPE html>
<html>
<head>
<title>BMI Calculator</title>
</head>
<body>
Weight:-<input type="text" id="wtxt"><br>
Height:-<input type="text" id="htxt"><br>
BMI:-<input type="text" id="bmitxt"><br>
<input type="reset" value="clear"><br>
<button onclick="calcbmi()">Calc BMI</button>
<script type="text/javascript">
function calcbmi(){
var w=parseInt(document.getElementById('wtxt').value);
var h=parseInt(document.getElementById('htxt').value);
var z=w/(h*h);
document.getElementById('bmitxt').value=z;
}
</script>
</body>
</html>
You can see a fiddle here

Related

There's a box supposed to pop up after clicking the "Click Me" button

I was working on variables and loop frames and stumbled across this problem. I tried switching some things around but none have succeeded. I put the code in a validator and it showed the document as valid.
Whats missing?
Here's the code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
<script type="text/javascript">
function substitute() {
var myValue = document.getElementById('myTextBox').value
if (myValue.length == 0) {
alert('Please enter a real value in the text box!');
return;
}
var myTitle = document.getElementById('title');
myTitle.innerHTML = myValue;
}
</script>
</head>
<body>
<h1 id="title">JavaScript Example</h1>
<input type="text" id="myTextBox" />
<input type="submit" value="Click Me" onclick="substitute" />
</body>
</html>
Mentioning the name of a variable holding a function doesn't call the function. You have to actually call it explicitly.
This is usually done by placing () after the reference to the function.
onclick="substitute()"

How to get javascript to print text input to console

I am new to javascript programming so am hoping that this is a simple issue... I'm wanting my webpage to allow a user to input a music track name and artist in two separate fields and once you hit 'go' the javascript will run and parse the input into a string. To test I have tried to see if these inputs are being taken and I have tried to print them to console, however nothing is being printed to the console.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Spotify</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main class="main-container">
<div class="header">
<p>TrackSelector</p>
</div>
<section>
<div class="form">
<form action="">
<input type="textt" class="track" placeholder="Enter track..." />
<input type="texta" class="artist" placeholder="Enter artist..." />
<button type="button" class="submit-btn">GO</button>
</form>
</div>
</section>
</main>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
Javascript file:
const app = {};
//Allow the user to enter names
app.events = function() {
$('form').on('button', function(e){
e.preventDefault();
let tracks = $('input[type=textt]').val();
let artists = $('input[type=texta]').val();
console.log(tracks);
console.log(artists);
});
};
//
//
app.init = function(){
app.events();
};
$(app.init);
I believe I have specified to take in the correct inputs and specified the correct button reference, have played around to try out other methods but I'm still quite stuck... any ideas?
Replace
$('form').on('button', function(e){
with
$('form .submit-btn').on('click', function(e){
jQuery .on() expects event name as its first argument.
There is no input type type="textt" and texta. There are only predefined types like text, email, password, checkbox and so on... So make type "text" in both inputs and for reference use id: <input id="my_track" type="text">. Then in javascript get value by $('#my_track').val(); To handle submit use $('form').on('submit', func)

Adding +1 to variable

So the way this code is supposed to work is like this, when I click the button I am going to add +1 to the variable antal and the second time when I press the button it should add another +1 making it 2.
Now the problem is that every time I push the button I instead get another 1 so the second time I have 11 and the third 111 I've tried everything but I cant get it right.
I can understand that there is a simple fix to this but I am quite new, thanks in advance for your answers. =)
<html>
<head>
<title>Uppgift 2</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script Language="JavaScript">
var antal = 0;
var $antalClick = {};
$antalClick.click = function() {
var antal = Math.round(document.getElementById("antal").value += 1);
};
</script>
</head>
<body>
<form name="formone">
<input type="button" value="resultat" onClick="$antalClick.click ();"/>
<input type="text" id="antal"/>
</form>
</body>
</html>
The problem is it is interpreting it as a string. You have to force it to be a number with parseInt()
Try
Math.round(parseInt(document.getElementById("antal").value) + 1);

Javascript Global Variables Not Working as expected. Help?

I am new to Javascript. I am facing a problem with global variables. I can't figure out that why the global variables are not working as the code looks ok. Please Help me solve this problem.
I will breifly explain the code first.I have some text on a page which changes to text field when clicked. When I define the variables inside the functions body the code starts working fine. When these variables are defined globally as in the following code, the console displays this error: the variable is not defined. Here my code:
<!DOCTYPE HTML>
<html>
<head>
<title>Span to Text Box - Demo - DOM</title>
<script type="text/javascript" language="javascript">
var textNode = document.getElementById('text');
var textValue = textNode.firstChild.nodeValue;
var textboxNode = document.getElementById('textbox');
var doneButton = document.getElementById('done');
function change()
{
textboxNode.setAttribute('value', textValue);
textNode.style.display = 'none';
textboxNode.setAttribute('type','text');
doneButton.setAttribute('type','button');
}
function changeBack()
{
textNode.firstChild.nodeValue = textboxNode.value;
textNode.style.display = 'block';
textboxNode.setAttribute('type', 'hidden');
doneButton.setAttribute('type','hidden');
}
</script>
</head>
<body>
<p id="text" onClick="change()">Click me!</p>
<form onSubmit="return false;">
<input type="hidden" id="textbox" />
<input type="hidden" id="done" onClick="changeBack()" value="Done" />
</form>
</body>
</html>
Please Help!
Thanks in Advance.
As Adam said, the issue is that you are running javascript on the document before the document has been loaded. There are a number of ways to fix this, but the simplest is to just move your javascript code to the end of the body so the document has already been parsed and is ready before your code runs like this:
<!DOCTYPE HTML>
<html>
<head>
<title>Span to Text Box - Demo - DOM</title>
</head>
<body>
<p id="text" onClick="change()">Click me!</p>
<form onSubmit="return false;">
<input type="hidden" id="textbox" />
<input type="hidden" id="done" onClick="changeBack()" value="Done" />
</form>
<script type="text/javascript" language="javascript">
var textNode = document.getElementById('text');
var textValue = textNode.firstChild.nodeValue;
var textboxNode = document.getElementById('textbox');
var doneButton = document.getElementById('done');
function change()
{
textboxNode.setAttribute('value', textValue);
textNode.style.display = 'none';
textboxNode.setAttribute('type','text');
doneButton.setAttribute('type','button');
}
function changeBack()
{
textNode.firstChild.nodeValue = textboxNode.value;
textNode.style.display = 'block';
textboxNode.setAttribute('type', 'hidden');
doneButton.setAttribute('type','hidden');
}
</script>
</body>
</html>
The error is likely caused by grabbing DOM nodes before they're ready:
var textNode = document.getElementById('text');
This is likely returning either null or undefined since that DOM element hasn't been created yet.
Putting this script at the end of your body should solve your problem.
Or, if you'd like to use jQuery, you can do all this in
$(document).ready(function() {
var textNode = document.getElementById('text');
}

Adding data dynamically to a HTML page

In a htmlpage using jQuery or JavaScript how can the following be achieved?
User types in a question in a textarea and press on enter button, then the same question should be displayed dynamically in the page below the textarea and the user can enter as many questions.
And when the user is done the page is submitted through a submit button.
Can you give a small hint of how this can be done?
Try this to get started :
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#textareabutton').click(function(){
var q = $('#textarea').val(),
$p = $('<p>').html( q );
$('#questions').append( $p );
});
$('#submit').click(function(){
var tab;
tab = $('#questions p').serializeArray();
// now do something with $.ajax to submit the questions
$.post("myphp.php",tab,function(resp){
// what do I do with the server's reply ???
});
});
});
</script>
<style type="text/css">
</style>
</head>
<body>
<textarea id='textarea'></textarea>
<button type='button' id='textareabutton'>Add question</button>
<div id='questions'></div>
<button type='button' id='submit'>Submit questions</button>
</body>
</html>
Use the innerHTML property of a div to add the questions to.

Categories