Hi I'm new to Javascript, having problem creating and adding a new to the DOM. (I want to do this with native javascript not jquery).
When I click the "Calculate" button, I very briefly see the Text flash on the screen and then disappear. Nothing added to the DOM.
Here is my JS script:
function makeResponseBox() {
document.getElementById("calculate").onclick = function()
{
var responseBox = document.createElement("DIV"); //create <div>
var para = document.createElement("P");//create <p>
var text = document.createTextNode("Text");//
para.appendChild(text);//append text to para
var newDiv = responseBox.appendChild(para);// append <p> to <div> and assign to variable
document.body.appendChild(newDiv);//append as child to <body>
}
}//close function (makeResponseBox)
window.onload=makeResponseBox;
Here is my HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Add Element to DOM</title>
<script src="calculate.js"></script>
</head>
<body id="main">
<h1>Add Element to DOM</h1>
<form id ="form">
<fieldset>
<input type="submit" value="Calculate" id="calculate" />
</fieldset><!-- close fieldset -->
</form><!-- close form -->
</body>
</html>
It's because the form is submitted so the page is reloaded
You need to add a parameter to your listener , say function(e) and call e.preventDefault() at the beginning of the listener.
example:
document.getElementById("calculate").onclick = function(e)
{
e.preventDefault();
var responseBox = document.createElement("DIV"); //create <div>
var para = document.createElement("P");//create <p>
var text = document.createTextNode("Text");//
para.appendChild(text);//append text to para
var newDiv = responseBox.appendChild(para);// append <p> to <div> and assign to variable
document.body.appendChild(newDiv);//append as child to <body>
}
Or you could also change the type of your button to remove the submit function
<input type="button" value="Calculate" id="calculate" />
But then your <form> become useless and you could remove it
change your submit type to button which will avoid the reload
<input type="submit" value="Calculate" id="calculate" />
to
<input type="button" value="Calculate" id="calculate" />
and if you want to submit the form handle it from js
Related
I know this may be a dumb question to some but I am pretty new to this and trying to learn. I have been stuck on this for days and couldn't figure it out so I came here for help. Whenever I hit the button it doesn't display my input at all. I want to make it that when the user clicks the button their input will show up in an ol list.
let form = document.getElementById("todo");
let list = document.getElementById("myList");
let input = document.getElementById("add1");
let input2 = document.getElementById("add2");
let button = document.getElementById("button");
let id = 1;
button.addEventListener("click", addToDo)
list.addEventListener("click", removeEvent)
function addToDo (e) {
let text = input.value;
let textAdd = input2.value;
let item = `<li class="del">
${text} ============= ${textAdd} <button class="del">Delete</button>`
list.insertAdjacentHTML("beforeend",item);
id++;
document.getElementById("add1").value = "";
document.getElementById("add2").value = "";
}
function removeEvent(e) {
if(e.target.classList.contains("del")) {
list.removeChild(e.target.parentElement);
list.removeChild(list);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<h1 id="name">Todo List</h1>
<link href="project.css" rel="stylesheet"/>
</head>
<body>
<div id="todo">
<h1>Name</h1>
<input type="text" id="add1" placeholder="Title">
<br>
<h1>Add Reminder</h1>
<input type="text" id="add2" placeholder="Notes">
<button id="button">Submit</button>
</div>
<ol id="myList">
</ol>
<script src="pro.js"></script>
</body>
</html>
There is something "special" about buttons within a form.
If your HTML looks like:
<form>
<input placeholder="enter some text">
<button>Click me</button>
</form>
Your button will submit the form and therefore reset it.
I guess you would expect the form to have some crucial properties to do so, namely 'action' and 'method' (to send the data in your inputs to some remote address - because that's the main concern of forms).
If you want your button to just be a button, use the following:
<form>
<input placeholder="enter some text">
<button type="button">Click me</button>
</form>
And you'll see: nothing happens.
I've created a StackBlitz here for you (just look at the HTML file). With type="button", more and more inputs are added to the form. If you omit this, you can see the input is added, and immediately after it, the form resets itself (sending a GET request to '/' and refreshing everything - but that's something for another question).
I'm trying to make a table in Javascript that does not use a table element, and I'm using pure vanilla nodeJS. I can get a new row to show up very briefly, but it disappears when I hit the button that made it show up in the first place. My code is:
<!DOCTYPE html>
<html>
<body>
<h1> Title Tests </h1>
<div id="Experiments">
<form id="Exp">
<input type="text" name="url box" placeholder="publisher URL"><br>
<div class="Title">
<input type="text" name="title box" placeholder="Test Title"><br>
</div>
<button id="addButton" onclick="newRow()">+</button><br>
<input type=submit value="Submit">
</form>
</div>
<script>
function newRow(){
var number = 2;
var newTitleRow = document.createElement('div');
newTitleRow.setAttribute('id',`Title${number}`);
var newBT = document.createElement('input');
newBT.setAttribute('type','text');
newBT.setAttribute('name',`title box ${number}`);
newBT.setAttribute('placeholder','Test Title');
newTitleRow.appendChild(newBT)
var button = document.querySelector("#addButton");
button.before(newTitleRow);
number++;
}
</script>
</body>
</html>
The problem is that you're using a html <button> inside a <form> element. This means it will automatically act as a submit button unless you declare it to be something different. So as soon as you push the + button it will try to submit the form to an undefined URL.
To work around you need to define that + button to be of type "button" like:
<button type="button" id="addButton" onclick="newRow()">+</button><br>
I am trying to combine data from two HTML forms and then post it as a single form which is working fine except that some elements are not being copied from one form to the other. I have defined the following javascript function to combine form elements:
var form = document.forms['auth_form'];
var issuedata = window.opener.document.getElementById('Create').elements;
for (var i = 0; i < issuedata.length; i++) {
var data = issuedata[i];
alert(data.innerHTML);
if(data.type !== "submit")
form.appendChild(data);
}
Actual files
This is the first form:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
var childWindow = null;
function child_open() {
childWindow = window.open('new.html', "_blank",
"resizable=no,width=600, height=280,top=200,left=200");
}
function parent_disable() {
if (childWindow && !childWindow.closed)
childWindow.focus();
}
</script>
</head>
<body onclick="parent_disable();">
<input type="button" value="Create Jira Ticket" onclick="child_open()" />
<form name="auth_form" id="Create" method="post">
<input name="bug_status" value="NEW" type="hidden">
<input name="rep_platform" value="All" type="hidden">
<input name="component" value="AFAS" type="hidden">
<input name="bug_severity" value="Beeper Call" type="hidden"/>
<input type="hidden" name="comment" value="hello hi"><br>
</form>
</body>
</html>
and this is second form:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
var count = 0;
function submit_and_close() {
var form = document.forms['auth_form'];
var issuedata = window.opener.document.getElementById('Create').elements;
for (var i = 0; i < issuedata.length; i++) {
var data = issuedata[i];
alert(data.innerHTML);
if(data.type !== "submit")
form.appendChild(data);
}
alert(form.innerHTML);
form.submit();
// close the window after form submission is complete.
var docLoaded = setInterval(function() {
if (document.readyState !== "complete") {
return;
}
clearInterval(docLoaded);
//window.close();
}, 30);
}
</script>
</head>
<body>
<header>
<div id="dialog" title="JIRA Dialog">
<h1>JIRA Credentials</h1>
</div>
</header>
<div>
<form name="auth_form" id="auth_form" method="post">
<label> User Name: </label> <input type="text" name="username"><br>
<label> Password: </label> <input type="password" name="password"><br>
<input type="button" value="Log In" onclick="submit_and_close()">
</form>
</div>
</body>
</html>
For example I am not able to see the following elements being copied over from 'Create' form to 'auth_form' in second html page.
<input name="rep_platform" value="All" type="hidden">
<input name="bug_severity" value="Beeper Call" type="hidden"/>
Even after spending sometime debugging, I am not able to figure out why some elements are being succesfully copied while others not.
.elements returns a live collection of elements. When you append an element from the collection, it gets removed from the collection, so your index i into the collection get out of sync, and therefore every other element gets skipped.
Instead, just append the first element from the collection until the collection is empty. (Just detach the submit button element when it is encountered). Alternatively, loop through the collection from last to first rather than first to last.
(querySelectorAll() works because it returns a static collection, rather than a live one.)
Try changing your second form from ...
var issuedata = window.opener.document.getElementById('Create').elements;
to
var issuedata = window.opener.document.querySelectorAll('input[name]');
... and replace all innerHTML with outerHTML
Trying to change text color and background color of the text according to what I write in the textbox. Seems to work briefly; it shows me the color for a split second, like a quick snap and that's it.
<!DOCTYPE html>
<html>
<head>
<title>Prelab5 Ex1</title>
<style>
</style>
</head>
<body>
<h2>Prelab5 Ex1</h2>
<form method="post">
<input type="text" name="background" id="background"/><input type="submit" value="Background" onclick="changeBack();"/>
<br/>
<input type="text" name="text" id="text"/><input type="submit" onclick="changeText();" value="Text"/>
<br/>
<div id="content">Some text</div>
</form>
<script>
var DivText = document.getElementById("content");
function changeBack(){
var backColor = (document.getElementById("background").value);
DivText.style.backgroundColor= backColor;
}
function changeText(){
var textColor = (document.getElementById("text").value);
DivText.style.color = textColor;
}
</script>
</body>
</html>
Your onclick handlers for your submit buttons don't return false so your form is submitted resetting the page. You could add return false like
var DivText = document.getElementById("content");
function changeBack() {
var backColor = (document.getElementById("background").value);
DivText.style.backgroundColor = backColor;
}
function changeText() {
var textColor = (document.getElementById("text").value);
DivText.style.color = textColor;
}
<!DOCTYPE html>
<html>
<head>
<title>Prelab5 Ex1</title>
</head>
<body>
<h2>Prelab5 Ex1</h2>
<form method="post">
<input type="text" name="background" id="background" />
<input type="submit" value="Background" onclick="changeBack(); return false" />
<br/>
<input type="text" name="text" id="text" />
<input type="submit" onclick="changeText(); return false" value="Text" />
<br/>
<div id="content">Some text</div>
</form>
</body>
</html>
Your "submit" input performs the action on the form, which is currently set to "post". This will post the form to the same page (and cause a refresh).
You can override the default functionality by adding return false; to the ONCLICK attribute on all input type= "submit" elements.
In other words, this:
needs to become this:
<input type="submit" onclick="changeText();" value="Text"/>
but why use input type = submit at all?
You can just as easily use a link or button without the form:
<a href="#" onclick="changeText();"/>Test</a>
or
Click me!
which will do the same thing without needing to override the a forum action :)
Below is the HTML code I am playing with. All it does is create an element with two buttons: "Element1" (TitleButton) and "Add". By clicking on "Add" the element is cloned and assigned id="element 2". What I am not able to do is assign value "Element2" for the TitleButton of the cloned element. How can I do it, preferably inside addNode() function? If it is not possible then what are other ways? Thanks
<HTML>
<HEAD>
<TITLE>Dynamically add Textbox, Radio, Button in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
function addNode(element) {
var adding_element = element.parentNode;
var added_element=adding_element.cloneNode(true);
added_element.setAttribute("id","element 2");
var cont = adding_element.parentNode;
cont.appendChild(added_element);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<div name="container" id="container">
<div name="element 1" id="element 1">
<input type="button" value= "element1"; name="TitleButton" />
<input type="button" value="Add" name="add[]" onclick="addNode(this)" />
</div>
</div>
</FORM>
</BODY>
</HTML>
You can use firstElementChild property.
var id = 2;
function addNode(element) {
var adding_element = element.parentNode;
var added_element = adding_element.cloneNode(true);
added_element.setAttribute("id", "element" + id);
added_element.firstElementChild.setAttribute('value', 'element ' + id);
var cont = adding_element.parentNode;
cont.appendChild(added_element);
id++;
}
http://jsfiddle.net/SUkYg/1/