Javascript display innerHTML on the same page - javascript

So I am testing the permute function of D3.js and it works just fine.
The issue I am having is to display the results on the same page using innerHTML, it always reloads in order to display.
I am probably missing a detail here, can someone help?
permute.html:
<html>
<head>
<meta charset="UTF-8">
<script language="JavaScript">
function* permute(keys) {
var size = keys.length,
c = Array(size).fill(0),
i = 1;
yield keys;
while (i < size) {
if (c[i] < i) {
var k = i % 2 && c[i];
[keys[i], keys[k]] = [keys[k], keys[i]];
c[i]++;
i = 1;
yield keys;
} else {
c[i++] = 0;
}
}
}
function showPermutations(){
var input = document.getElementById("keys").value;
document.getElementById('results').innerHTML=input;
for (var words of permute(input.split(/\s+/))) {
document.write(words.join(''));
document.write("<br>");
}
}
</script>
<body>
<form>
<label><b>Keywords</b></label></br>
<input type="text" id="keys" name="keys"></br>
</form>
</br>
<input type="submit" value="Permute" onclick="showPermutations();"></br>
<p><span id='results'></span></p>
</head>
</body>
</html>
Some of you pointed out the issue is caused by the submit button, but in this other example, using submit, the JS works just fine on the same page:
test.html
<html>
<head lang="en">
<meta charset="UTF-8">
<script language="JavaScript">
function showInput() {
document.getElementById('display').innerHTML =
document.getElementById("user_input").value;
}
</script>
</head>
<body>
<form>
<label><b>Enter a Message</b></label>
<input type="text" name="message" id="user_input">
</form>
<input type="submit" onclick="showInput();"><br/>
<label>Your input: </label>
<p><span id='display'></span></p>
</body>
</html>

When you click the submit button, the page will automatically reload. You should prevent that by calling the preventDefault method of the event object that is passed to the event handler, in your case, that handler would be showPermutations.
Make that function receive one argument, called e, ev, or event (as it is normally called) and inside it, execute the preventDefault method before anything else.
function showPermutations(e){
e.preventDefault();
...
}
Or don't use a submit button.

Related

Why does this span tag only changes for less than a second?

This is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>date of birth</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<main>
<div id="div1">
<h1>Age in days</h1>
</div>
<form id="user_input">
<input id="age_years" type="number" placeholder="Put your age in years">
<input type="submit" class="btn btn-success" id="submit_button" onclick="ageInDays()">
</form>
<div>
<p id="finalText">This is your age in days: <span id="span">0</span> </p>
</div>
</main>
<script src="app.js"></script>
</body>
</html>
This is my Javascript:
"use strict"
function ageInDays() {
let ageInYears = document.getElementById("age_years").value;
let ageDays = ageInYears * 365;
// para.appendChild(text);
document.getElementById("span").textContent= ageDays;
}
When I run the code, it only shows the answer for a split second and then it goes away. Does anybody know why this happens?
The page reloads after showing the value in span because it is the default behavior while submitting forms, if you simply want to calculate the age in days and show it into span tag and don't want the values to be submitted using form then you can simply do this, just add onsubmit="return false" to your form element,
Like this
<form id="user_input" onsubmit="return false">
Hope it helps!
It actually submits the form by defaults, hence it refreshes the page, try to prevent the action:
in your HTML:
<input type="submit" class="btn btn-success" id="submit_button" onclick="ageInDays(event)">
in your JS:
function ageInDays(e) {
e.preventDefault(); // prevents from reloading the page
let ageInYears = document.getElementById("age_years").value;
let ageDays = ageInYears * 365;
// para.appendChild(text);
document.getElementById("span").textContent= ageDays;
}
It may be possible that javascript is running before HTML is rendered. Try this one is .js file.
window.onload = function(){
"use strict"
function ageInDays() {
let ageInYears = document.getElementById("age_years").value;
let ageDays = ageInYears * 365;
// para.appendChild(text);
document.getElementById("span").textContent= ageDays;
}
});

Clear input field on page refresh

I have some Input fields on my page, these fields are already filled when I refresh the page.
How can I clear the pre-filled input fields without using reset button on page refresh?
function add() {
var num1, num2, c;
num1 = Number(document.getElementById("a").value);
num2 = Number(document.getElementById("b").value);
c = num2 + num1;
document.getElementById("answer").value = c;
}
<!doctype html>
<html>
<title>
addition WEBSITE
</title>
<body>
<div align="center">
<h1>addition</h1>
a= <input id="a"> b= <input id="b">
<button onclick="add()">Add</button> Sum= <input id="answer">
</div>
</body>
</html>
You can clear the fields on window.onload .
<!doctype html>
<html>
<title>
addition WEBSITE
</title>
<head>
</head>
<script >
window.onload = function(){
document.getElementById("a").innerHTML = "";
document.getElementById("b").innerHTML = "";
}
function add()
{
var num1,num2,c;
num1= Number(document.getElementById("a").value);
num2= Number(document.getElementById("b").value);
c=num2+num1;
document.getElementById("answer").value=c;
}
</script>
<body>
<div align="center">
<h1>
addition
</h1>
a= <input id="a">
b= <input id="b" >
<button onclick="add()">Add</button>
Sum= <input id="answer" >
</div>
</body>
</html>
Your code should be better.
Anyway, if you want the fields to be empty when refreshing the page, create an anonymous function called by itself like this:
function () {
document.getElementById('a').value = "";
}
Get the other input elements and do the same inside this function.
Happy coding !!

value is not displayed when enter the value to the text box

This is works fine when the form does not have any value. But, Once i entered the value on the textbox, it still alert the same messages i.e it is omitting 'You must enter value' for both cases,see at the if else statement. what is the mistake on the below code?
<!doctype html>
<html>
<head>
<title>A Basic Example</title>
</head>
<body>
<p>A Basic Form Example</p>
<form action="#">
<p>Name <em>(Required)</em>: <input id="textbox1" name="textname" type="text" /></p>
<p><input id="submitbutton1" type="submit" /></p>
<script type="text/javascript">
var item = document.getElementById("textbox1").value.length;
var item1 = document.forms[0].textname;
function formValid() {
if (item == 0) {
alert("You must enter value");
}
else {
alert(item1);
}
}
var formEl = document.getElementById("submitbutton1");
formEl.addEventListener("click", formValid());
</script>
</form>
</body>
</html>
You are fetching the length of the value when the page loads instead of when the the function runs.
Move
var item = document.getElementById("textbox1").value.length
inside the function.
Use this syntax in addEventListener formEl.addEventListener("click", formValid,false);
Also replace var item inside the function formValid().
Here is the fiddle
try this
<!doctype html>
<html>
<head>
<title>A Basic Example</title>
</head>
<body>
<p>A Basic Form Example</p>
<form action="#">
<p>Name <em>(Required)</em>: <input id="textbox1" name="textname" type="text" /></p>
<p><input id="submitbutton1" type="submit" /></p>
<script type="text/javascript">
var item1 = document.forms[0].textname;
var formEl = document.getElementById("submitbutton1");
function init() {
formEl.addEventListener("click", formValid());
}
function formValid() {
var item = document.getElementById("textbox1").value.length;
if (item == 0) {
alert("You must enter value");
}
else if {
alert(item1);
}
}
</script>
</form>
</body>
</html>

Why does this give "undefined" error?

I am trying to get the user to put something into the text area and the output should be what he wrote repeapiting x amount of times, but I get an error "document.forme is undefined".
Can you please help me understand why it is undefined?
My code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>input home work</title>
<script type="text/javascript">
var help= document.forme.tryout.value;
for (x=1; x<=10;x++){
function numberCheak (){
document.write("this is"+" "+help++);
}
}
</script>
</head>
<body>
<form name="forme">
<input name="tryout" type="text" />
<input type="button" value="click me" onClick="numberCheak();"/>
</form>
</body>
</html>
Ok, you have a few problems. The first is that you are trying to access a form element that doesn't exist yet: the script is above the form element, so the form doesn't exist when you try to get it. If you move the script to the bottom of the page it will work better.
Second, the loop should be inside the function, not wrapped around the function.
Third, document.write has weird side effects and causes the document to be rewritten and will stop the script from continuing correctly.
Here's my revised script
function numberCheak() {
var help = document.forme.tryout.value;
for (var x = 1; x <= 10; x++) {
document.getElementById("output").innerHTML += help;
}
}
and the HTML form that goes with it
<form name="forme" id="forme">
<input name="tryout" type="text" />
<input type="button" value="click me" onclick="numberCheak();" />
<span id="output"></span>
</form>
You can see it in action on jsFiddle.
Forms are stored in collection and can be accessed like this:
var form = document.forms[i];
or
var form = document.forms[name];
In your case, i is 0 and name is forme.

onclick event result disappears

When I use this code the console.log and the value in the field disappear right away.
window.onload = bereken;
function bereken(){
var knop = document.getElementById('berekenKnop').onclick = function (){
var aantalKm = document.getElementById('bereken');
console.log(aantalKm.value);
};
}
How can I prevent that from happening. Or what am I doing wrong?
The final goal will be to append the result of a calculation by the value of the field into another field.
edit:
<html>
<head>
<script src="bereken.js"></script>
</head>
<body>
<form id="berekenForm">
Bereken: <input type="text" name="bereken" id="bereken"/><br />
<input type="submit" value="Bereken" id="berekenKnop"/>
</form>
</body>
</html>
The submit button is doing its default task. i.e. submitting the form. Try handling that.
Value in the field 'bereken' not disappearing.See the code below. If this is not the expected answer, please, Update the question with question in details:
<html>
<head>
<script type="text/javascript">
window.onload = bereken;
function bereken(){
var knop = document.getElementById('berekenKnop').onclick = function (){
var aantalKm = document.getElementById('bereken');
console.log(aantalKm.value);
};
}
</script>
</head>
<body>
<div id="berekenKnop">
Click Here to console value
</div><br/>
<input type="text" value=" bereken value" id="bereken" />
</body>
</html>

Categories

Resources