getElementById doesn't work - javascript

I'm new to this website and I'm just learning how to code. My program doesn't write anything or create an input, can someone help me and spot the mistake?
<html>
<head><title>array exchange</title></head>
<body>
<form id="ne" >
number of array elements: <input type="number" name="el_array" ><br>
<input type="submit" value="execute" onsubmit="create()">
</form>
</body>
<script>
function create(){
var numel = document.getElementById("ne");
var x = document.createElement("INPUT");
x.setAttribute("type", "number");
}
</script>
</html>

You need to append child then it will be reflected in DOM
numel.appendChild(x)
Also use type="button" instead of type="submit" and onclick event handler
<input type="button" value="execute" onclick="create()">
function create() {
var numel = document.getElementById("ne");
var x = document.createElement("INPUT");
x.setAttribute("type", "number");
numel.appendChild(x);
}
<form id="ne">
number of array elements: <input type="number" name="el_array"><br>
<input type="button" value="execute" onclick="create()">
</form>

You can read about the usage of the form tag as well for better understanding:
https://www.w3schools.com/TAgs/tag_form.asp
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form

İ recommend starting read from MDN.My opinion MDN The best documentation for Javascript:
https://developer.mozilla.org/bm/docs/Web/JavaScript/Guide/Introduction

var input = document.createElement("input");
input.type = "submit";
document.body.appendChild(input);
input.addEventListener("click",function createEl(){
var numel = document.getElementById("ne");
var x = document.createElement("INPUT");
x.setAttribute("type", "number");
numel.appendChild(x);
});
<form id="ne" >
number of array elements: <input type="number" name="el_array" >
<br>
</form>

Related

To get the nearest submit button using javascript

Following is a test code of what i want to achieve. I want to find the value of submit button when cancel is clicked. here i have use for loop. is there any other way without iterating.
<!DOCTYPE html>
<html>
<body>
<ol>
<input type="text" name="txt1">
<input type="text" name="txt2">
<input type="text" name="txt3">
<li><input type="button" value="cancel" name="cancel" onclick="myFunction()"></li>
<li><input type="button" value="undo" name="undo"></li>
<li><input type="submit" value="send mail" name="submit"></li>
</ol>
<script>
function myFunction() {
var elementsLI = document.getElementsByTagName('li');
var length = document.getElementsByTagName('li').length;
for(var i = 0; i <= length ; ++i){
if(elementsLI[i].childNodes[0].type == "submit"){
alert(elementsLI[i].childNodes[0].value);
}
//var y = elementsLI.childNodes[i].type == "submit";
}
}
</script>
</body>
</html>
You can get it using querySelector() method with attribute equals selector.
var submit = document.querySelector('li [type="submit"]');

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

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.

Adding textbox on button click with 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>

Categories