Adding textbox on button click with javascript - javascript

I'm working on a web form with a textbox for pets and an "add pet" button. Each time the button is clicked, an additional textbox should be displayed below the original one.
I'm assuming this would be accomplished with an onclick event, but I can't figure out how to get it to work.
Here is the code I have so far:
<html>
<head>
<title>Project 4</title>
</head>
<body>
<form name="myForm" onsubmit="return validateForm()">
Pets: <input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
<br>
</form>
<script type="text/javascript">
function makeCopy() {
var copy = <input type="text">;
return copy;
}
</script>
</body>
</html>
There are other pieces to this as well, but none of them affect this particular problem I am having so didn't see the need to include the full code as it's fairly long.
Any suggestions are greatly appreciated.
Update:
I realize after reading the answers that I should've included more of my code to give you guys a better idea of the actual layout of my page. I have several text fields in my form and need the additional textboxes to be displayed right below the original "pets" textbox. Here's a jfiddle I threw together to give you guys a better idea of the layout. http://jsfiddle.net/a5m8nqwk/

Something like this?
<form name="myForm" id="myForm" onsubmit="return validateForm()">
Pets: <br />
<input type="text" id="pets" />
<input type="button" id="addPet" value="Add Pet" />
<br/>
</form>
document.getElementById("addPet").onclick = function() {
var form = document.getElementById("myForm");
var input = document.createElement("input");
input.type = "text";
var br = document.createElement("br");
form.appendChild(input);
form.appendChild(br);
}
Edit: I'd suggest using a table to style the input boxes, keep them in line. FIDDLE

You could easily add elements to the DOM:
function createPetField() {
var input = document.createElement('input');
input.type = 'text';
input.name = 'pet[]';
return input;
}
var form = document.getElementById('myForm');
document.getElementById('addPet').addEventListener('click', function(e) {
form.appendChild(createPetField());
});

function add(type) {
//Create an input type dynamically.
var element = document.createElement("input");
var text = document.getElementById("textId");
//Append the element in page (in span).
text.appendChild(element);
}
h1 {
color: #0000ff;
}
<h1>KIAAT</h1>
<b>Adding textbox on button click with javascript</b>
<br><br>
<form>
<input placeholder="text" name="element" hidden> </input>
<input type="button" value="Click Me" onclick="add(document.forms[0].element.value)"/>
<span id="textId"> </span>
</form>

Related

Javascript - How to add form's input into the dom properly?

I'm just trying to make a simple javascript form where everytime you type and submit something, it shows up in the page.
<form id="myForm">
<input id="text" type="text" name="name" value="">
<input id="submit" type="submit">
</form>
javascript:
document.getElementById("myForm").addEventListener('submit', function(){
var input = document.getElementById("text")
var output = input.value;
var printOutput = document.createElement('h1');
printOutput.innerHTML = output;
document.body.appendChild(printOutput);
});
This shows up for a second then disappears. I understand it's happening because the dom manipulation is happening inside the submit event. But I'm not sure how to go around that.
My first instinct was to use
return output;
then reference the whole function once I appendChild from outside it. But that didn't work either. I'm guessing cause It's an Eventlistener and not a normal function... any ideas on how to go with this?
You are ignoring the form primordial sense that is to send data over a server.
You don't need aform for what you intend. you need only input elements and a handler on the button.
function handler (){
var input = document.getElementById("text")
var output = input.value;
var printOutput = document.createElement('h1');
printOutput.innerHTML = output;
document.body.appendChild(printOutput);
document.getElementById("text").value='';
}
document.getElementById("submit").addEventListener('click', handler);
document.getElementById("text").addEventListener('keypress', function(e){ (e.charCode == 13) && handler();});
<div id="myForm">
<input id="text" type="text" name="name" value="">
<input id="submit" type="submit">
</div>
Add return false; at the end of the event listener. This stops the submit from actually happening which refreshes the page
Try this instead:
document.getElementById("myForm").addEventListener('submit', function(event){
event.preventDefault();
var input = document.getElementById("text")
var output = input.value;
var printOutput = document.createElement('h1');
printOutput.innerHTML = output;
document.body.appendChild(printOutput);
});
the simplest way of getting input and display on the same page is
function display()
{
var input=document.getElementById("text").value;
document.getElementById("display").innerHTML=input;
}
<form id="myForm">
<input id="text" type="text" name="name" value="">
<input id="submit" type="button" onclick=display() value="submit">
<div id="display"></div>
</form>
if you want to display multiple inputs i.e. each input entered by the user.
document.getElementById("display").innerHTML += input+"<br>";
Note: Always try to write easiest and shortest code for the optimized result.
yes it behaves how it should. it's form and what it does it submits all information to new page. you didn't provide action='' parameter and means it sends information on same page. when you click submit what happens is first you append h1 element and then it reloads, that's why it disappears. if you don't have other page to submit information get rid of forms.
<input id="text" type="text" name="name" value="">
<input id="submit" onclick='return getoutup();' type="submit">
<h1 id='output'></h1>
<script type="text/javascript">
function getoutup(){
document.getElementById('output').innerText=document.getElementById('text').value;
return false;
}
</script>
so you see that i have pre-created h1 tag, so you don't need much coding to append as function goes. just pre create with value of none and then change with one line of code. hope it helps. maybe it's not correct answer kind of changed your way.

Creating input elements and filling them with js script

I was trying to add some rows of input to my form so I will be able to post them to the back-end in one request, and also be able to add more of the same information type if need be
this is the code that I'm using:
<!DOCTYPE html>
<head>
</head>
<body>
<form action="#" method="post">
<input id="firstElement" type="text" name="firstElement" value="">
<button onClick="addRow()">add row</button><br>
<div id="container"></div>
<input type="submit" value="submit">
</form>
<script>
function addRow() {
var container = document.getElementById("container");
var myElement1 = document.getElementById("firstElement").value;
document.getElementById("firstElement").value = "";
var i = 0;
var input1 = document.createElement("input");
input1.type = "text";
input1.name= "myElement1"+ i;
input1.disabled = "true";
input1.value = myElement1;
container.appendChild(input1);
container.appendChild(document.createElement("br"));
i++;
}
</script>
</body>
this code shows the output for a second or less and then nothing...
The default type attribute of a button element is submit, so when you click the button you're actually submitting your form. Change that easily by specifying the type to be a button instead:
<button onClick="addRow()" type="button">add row</button>
jsFiddle example

Removing Elements using DOM

I am attempting to create an appear and disappear effect with an input. When the radio button is "no", the item should appear. When the radio button is "yes", the item should disappear. I have got the item to appear so far, but cannot get it to be removed through DOM. I have included my example on how I can remove my email which i commented out, but can't seem to remove the innerHTML or the input.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function myFunction() {
var label = document.createElement("label");
label.innerHTML = "<br>Shipment Cost : $";
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
var sp2 = document.getElementById("emailP");
var parentDiv = sp2.parentNode;
parentDiv.insertBefore(x, sp2);
parentDiv.insertBefore(label, x);
alert("Added Text Box");
}
function myFunction2() {
alert("Removed Textbox and Input");
anchor = document.getElementById("label");
anchor.parentNode.removeChild(anchor);
anchor2 = document.getElementById("INPUT");
anchor2.parentNode.removeChild(anchor2);
//THIS WORKS TO REMOVE EMAIL.
//anchor3 = document.getElementById("emailP");
//anchor3.parentNode.removeChild(anchor3);
}
</script>
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">
<p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" onclick="myFunction2()" />Yes
<input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;" />No
<p class="boldParagraph" id="emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<br>
<br>
<button>Submit</button>
</form>
</body>
</html>
It's not working, because the lines anchor = document.getElementById("label"); and anchor2 = document.getElementById("INPUT"); are looking for elements with the id label and input, but can't find them. Those are actually tag names.
You need to add an id to the elements you create in the first function:
label.setAttribute("id", "idForLabel");
x.setAttribute("id", "idForInput");
and then change the lines in the second function to:
anchor = document.getElementById("idForLabel");
anchor2 = document.getElementById("idForInput");

how to copy contents from one textbox in one form to another textbox in another form through JS

<form action="formoneaction" method="post">
<input type="text" id="t1" />
<button type="sumbit" class="btn">Insert</button>
</form>
<form action="formtwoaction" method="post">
<input type="text" id="t2" />
<button type="sumbit" class="btn">Insert</button>
</form>
<script>
var t1 = document.getElementById('t1');
t1.onkeyup = t1.onchange = function() {
document.getElementById('t2').value = this.value;
};
</script>
How can I get the script to work when the two elements are in separate forms? The script works when none of them are in forms.
I've never learned JS before so I may not understand very well when someone explains a bunch of jargon. Sorry but I'll try my best!
Try out below Code, which copies data from textbox to TextArea:
$("#textArea").append("\n * " + $("#textBox").val());
Working Demo

Creating text fields according to user's input in JavaScript Function

I want to create text fields according to user's input and show the text fields through JavaScript function but this code is not working!
<html>
<head>
<title>Create text Fields according to the users choice!</title>
<script type="script/JavaScript">
function createTextField(){
var userInput = parseInt(document.form2.txtInput.view);
for(var i=0; i<=userInput;i++)
{
document.write('<input type="text">');
}
}
</script>
</head>
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>
Input: <input type="text" name="txtInput">
<input type="button" name="btnInput" value="Create" onclick="createTextField();">
</form>
</html>
Please Replace this line:
var userInput = parseInt(document.form2.txtInput.view);
To
var userInput = parseInt(document.getElementsByName('txtInput')[0].value);
function createTextField(){
// alert(document.getElementById('txtInput').value);
var userInput = parseInt(document.getElementsByName('txtInput')[0].value);
for(var i=0; i<userInput;i++)
{
document.write('<input type="text">');
}
}
<html>
<head>
<title>Create text Fields according to the users choice!</title>
</head>
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>
Input: <input type="text" name="txtInput" id="txtInput">
<input type="button" name="btnInput" value="Create" onclick="createTextField();">
</form>
</html>
You shouldn't use document.write. The correct way to do it is to append the inputs to a div.
Demo on Fiddle
HTML:
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>Input:
<input type="text" name="txtInput" />
<input type="button" name="btnInput" value="Create" />
<div></div>
</form>
JavaScript:
var btn = document.getElementsByTagName("input")[1];
btn.onclick = function () {
var userInput = parseInt(document.getElementsByTagName("input")[0].value, 10);
for (var i = 0; i <= userInput - 1; i++) {
document.getElementsByTagName("div")[0].innerHTML += "<input type='text' />"
}
};
Jquery is better option to add dynamic input/div's easy to manipulate DOM.
Check the following code
<div class="box">
<label> Enter input value </label>
<input type="number" id="in_num"/>
<button type="button" id="submit"> submit </button>
<h3> Append input values</h3>
<div id="dynamicInput"></div>
</div>
$(document).ready(function(e){
$('#submit').click(function(){
var inputIndex = $('#in_num').val();
for( var i=0; i<inputIndex; i++)
{
$('#dynamicInput').append('<input type=text id=id_'+ i +'/>');
}
});
});
Demo URl: http://jsfiddle.net/sathyanaga/75vbgesm/3/
Change:
var userInput = parseInt(document.form2.txtInput.view);
To:
var userInput = parseInt(document.getElementById("txtInput").value);
And give the input textbox an id (I used "txtInput", but it can be anything).
I believe you also need to change the loop from, when I typed "2" it created 3 inputs instead of 2.

Categories