HTML DOM - element.appendChild() doesn't behave as I expect it to - javascript

link to code (js and css can be found through the page source): https://dl.dropboxusercontent.com/u/16952797/webdev/uppg1/kontakt.html
alt link: http://jsfiddle.net/DdQhk/ (although jsfiddle does not render the page properly)
relevant lines of code (function createFormBug() - line 31 to 66 in kontakt.js)
code:
function createFormBug() {
var form = document.createElement("form");
var fieldset = document.createElement("fieldset");
var legend = document.createElement("legend");
var labelFunction = document.createElement("label");
var labelInterface = document.createElement("label");
var labelComment = document.createElement("label");
var radioFunction = document.createElement("input");
radioFunction.type = "radio";
var radioInterface = document.createElement("input");
radioInterface.type = "radio";
var textarea = document.createElement("textarea");
var buttonSubmit = document.createElement("input");
radioInterface.type = "submit";
form.id = "formBug";
legend.textContent = "Bugg";
document.getElementById("divForm").appendChild(form);
form.appendChild(fieldset);
fieldset.appendChild(legend);
fieldset.appendChild(labelFunction);
fieldset.appendChild(radioFunction);
fieldset.appendChild(labelInterface);
fieldset.appendChild(radioInterface);
fieldset.appendChild(labelComment);
fieldset.appendChild(textarea);
fieldset.appendChild(buttonSubmit);
}
context: I'm trying to create a form dynamically by using js, unfortunately some elements aren't being appended for some reason.
partial output of generated html when run on Chrome (relevant section):
<div id="divForm">
<form id="formBug">
<fieldset>
<legend>Bugg</legend>
<label></label>
<input type="radio">
<label></label>
<input type="submit">
<label></label>
<textarea></textarea>
<input>
</fieldset>
</form>
</div>

I think your code is working pretty much as you might expect it to. The only obvious mistake is that you are setting radioInterface.type = "submit"; where you presumably mean buttonSubmit.type = "submit";.
It should be apparent that this works fine if you actually put some content in to make elements like label actually visible...
Something like this, perhaps?
var form = document.createElement("form");
var fieldset = document.createElement("fieldset");
var legend = document.createElement("legend");
var labelFunction = document.createElement("label");
labelFunction.textContent = 'Function'; // <-- added
var labelInterface = document.createElement("label");
labelInterface.textContent = 'Interface'; // <-- added
var labelComment = document.createElement("label");
labelComment.textContent = 'Comment'; // <-- added
var radioFunction = document.createElement("input");
radioFunction.type = "radio";
var radioInterface = document.createElement("input");
radioInterface.type = "radio";
var textarea = document.createElement("textarea");
var buttonSubmit = document.createElement("input");
buttonSubmit.type = "submit"; // <-- corrected
I believe your code to actually add them to the document should be working fine.

Related

HTML Javascript dynamically add and remove textboxes

I'm trying to add and remove text boxes dynamically using javascript and HTML.
I can get it to add and remove but sometimes the remove button doesn't work. when I inspect the element it says that there is no onclick value for the remove button. I don't understand why when I set the onclick in the add function.
Heres my code:
<div id="reqs">
<h3 align = "center"> Requirements </h3>
<script>
var reqs_id = 0;
function removeElement(elementId,elementId2) {
// Removes an element from the document
var element2 = document.getElementById(elementId2);
var element = document.getElementById(elementId);
element2.parentNode.removeChild(element2);
element.parentNode.removeChild(element);
}
function add() {
reqs_id++;// increment reqs_id to get a unique ID for the new element
//create textbox
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class","w3-input w3-border");
input.setAttribute('id','reqs'+reqs_id);
var reqs = document.getElementById("reqs");
//create remove button
var remove = document.createElement('button');
remove.setAttribute('id','reqsr'+reqs_id);
remove.onclick = function() {removeElement('reqs'+reqs_id,'reqsr'+reqs_id);return false;};
remove.setAttribute("type","button");
remove.innerHTML = "Remove";
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
This will work:
<div id="reqs">
<h3 align="center"> Requirements </h3>
</div>
<script>
var reqs_id = 0;
function removeElement(ev) {
var button = ev.target;
var field = button.previousSibling;
var div = button.parentElement;
div.removeChild(button);
div.removeChild(field);
}
function add() {
reqs_id++; // increment reqs_id to get a unique ID for the new element
//create textbox
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class", "w3-input w3-border");
input.setAttribute('id', 'reqs' + reqs_id);
input.setAttribute('value', reqs_id);
var reqs = document.getElementById("reqs");
//create remove button
var remove = document.createElement('button');
remove.setAttribute('id', 'reqsr' + reqs_id);
remove.onclick = function(e) {
removeElement(e)
};
remove.setAttribute("type", "button");
remove.innerHTML = "Remove" + reqs_id;
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
Fixed from my previous answer. Another option that may be necessary is to have each element know its exact place and be able to adjust itself based on what was added or removed. This enhancement will account for that by re-adjusting and ensuring your elements are always in order. (if desired)
See JSFiddle example.
Html
<div id="reqs">
<h3>Requirements</h3>
<button type="button" value="Add" onclick="javascript:add();">Add</button>
<br>
</div>
Javascript
function removeElement(e) {
let button = e.target;
let field = button.previousSibling;
let div = button.parentElement;
let br = button.nextSibling;
div.removeChild(button);
div.removeChild(field);
div.removeChild(br);
let allElements = document.getElementById("reqs");
let inputs = allElements.getElementsByTagName("input");
for(i=0;i<inputs.length;i++){
inputs[i].setAttribute('id', 'reqs' + (i+1));
inputs[i].setAttribute('value', (i+1));
inputs[i].nextSibling.setAttribute('id', 'reqsr' + (i+1));
}
}
function add() {
let allElements = document.getElementById("reqs");
let reqs_id = allElements.getElementsByTagName("input").length;
reqs_id++;
//create textbox
let input = document.createElement('input');
input.type = "text";
input.setAttribute("class", "w3-input w3-border");
input.setAttribute('id', 'reqs' + reqs_id);
input.setAttribute('value', reqs_id);
let reqs = document.getElementById("reqs");
//create remove button
let remove = document.createElement('button');
remove.setAttribute('id', 'reqsr' + reqs_id);
remove.onclick = function(e) {
removeElement(e);
};
remove.setAttribute("type", "button");
remove.innerHTML = "Remove";
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
let br = document.createElement("br");
reqs.appendChild(br);
}

Using onclick in javascript to create a new div inside a div created using onclick itself?

I created a div consisting of radio button inputs using onclick from a radio button input inside a form in php and then i again attempted to create another div using onclick from inside this created div but only the outer div is being created. Would like to know where i am wrong..
<input id="sub" type="radio" name="opt1" value="2" onclick="createDiv4()"> Academic User<br/>
function createDiv4() {
if(document.getElementById("acad_")==null)
{
var divi = document.createElement("div");
divi.id="acad_";
divi.style.height="100px";
//divi.style.marginTop="200px";
var cont = document.getElementById('contain');
cont.appendChild(divi);
var p = document.createElement("label");
var disp = document.createTextNode("Please select the type of User :");
p.appendChild(disp);
p.style.textSize="16px";
p.style.textAlign="left";
divi.appendChild(p);
var b1 = document.createElement("BR");
divi.appendChild(b1);
var ip = document.createElement("input");
ip.name="wo";
ip.value="1";
ip.type="radio";
ip.onclick="createDiv4_1()";
ip.style.marginRight="4px";
divi.appendChild(ip);
var labe = document.createElement("label");
var labe_val = document.createTextNode("Technical Institute");
labe.appendChild(labe_val);
divi.appendChild(labe);
var b = document.createElement("BR");
divi.appendChild(b);
var ip2 = document.createElement("input");
ip2.name="wo";
ip2.value="2";
ip2.type="radio";
ip2.style.marginRight="4px";
ip2.onclick="createDiv4_1()";
divi.appendChild(ip2);
var labe2 = document.createElement("label");
var labe_val2 = document.createTextNode("School");
labe2.appendChild(labe_val2);
divi.appendChild(labe2);
if(document.getElementById("govt")!=null)
{
var de = document.getElementById("govt");
de.parentNode.removeChild(de);
}
}
else
{
var divi1 = document.getElementById("acad_");
divi1.parentNode.removeChild(divi1);
}
}
</script>
<script>
function createDiv4_1() {
if(document.getElementById("school")==null)
{
var divi = document.createElement("div");
divi.id="school";
//divi.style.marginTop="200px";
var cont = document.getElementById('contain');
cont.appendChild(divi);
var p = document.createElement("label");
var disp = document.createTextNode("Please select the type of User for Workshop :");
p.appendChild(disp);
p.style.textSize="16px";
p.style.textAlign="left";
divi.appendChild(p);
var b1 = document.createElement("BR");
divi.appendChild(b1);
var ip = document.createElement("input");
ip.name="wo";
ip.value="1";
ip.type="radio";
ip.style.marginRight="4px";
divi.appendChild(ip);
var labe = document.createElement("label");
var labe_val = document.createTextNode("School Student");
labe.appendChild(labe_val);
divi.appendChild(labe);
var b = document.createElement("BR");
divi.appendChild(b);
var ip2 = document.createElement("input");
ip2.name="wo";
ip2.value="2";
ip2.type="radio";
ip2.style.marginRight="4px";
divi.appendChild(ip2);
var labe2 = document.createElement("label");
var labe_val2 = document.createTextNode("Teacher");
labe2.appendChild(labe_val2);
divi.appendChild(labe2);
var b2 = document.createElement("BR");
divi.appendChild(b2);
var ip2 = document.createElement("input");
ip2.name="wo";
ip2.value="2";
ip2.type="radio";
ip2.style.marginRight="4px";
divi.appendChild(ip2);
var labe3 = document.createElement("label");
var labe_val3 = document.createTextNode("Parent");
labe3.appendChild(labe_val3);
divi.appendChild(labe3);
if(document.getElementById("govt")!=null)
{
var de = document.getElementById("govt");
de.parentNode.removeChild(de);
}
}
else
{
var divi1 = document.getElementById("school");
divi1.parentNode.removeChild(divi1);
}
}
</script>
You arent calling the functions properly. Instead of :
ip.onclick= "createDiv4_1()";
This is only a string, it won't call it. You put it in quotes in the HTML but in JavaScript you don't need to. Also get rid of the parenthesis in JS. So use this :
ip.onclick= createDiv4_1;
Working fiddle : https://jsfiddle.net/thatOneGuy/xgvqwcq4/2/
I added a div with ID contain for this to work too.
according to your question title you have two option.
forget about onclikc inside the html and use normal js
document.getElementById("secondDiv").addEventListener("click", function () {
newFunctionI();
})
/*JQ version*/
$("#secondDiv").on("click", function () {
newFunctionI();
})
second way is: use jquery append() or html();
function yourFunctionI() {
$("#ID").append("<div id='secondDiv' onclick='newFunction()'> new </div>")
}

Google Chrome pattern regex not working when dynamically creating form with setCustomValidity

It seems dynamically adding customValidity is breaking the pattern validation. Is there any way to fix this issue using Javascript?
<html>
<head>
<title>Append validation issue</title>
<script>
function dothis(){
var f = document.createElement("form");
var i = document.createElement("input");
i.type = "text";
i.pattern = "[A-Z]{3}";
i.setCustomValidity("watch me break");
var s = document.createElement("input")
s.type = "submit";
f.appendChild(i);
f.appendChild(s)
document.getElementById("core").appendChild(f);
}
</script>
</head>
<body>
<div onclick="dothis()">click</div>
<div id="core"></div>
</body>
</html>
Using setCustomValidity will set the customError property to true, and thus the element will always be invalid.
So we should use setCustomValidity when text is invalid, and clear when valid.
function dothis(){
var f = document.createElement("form");
var i = document.createElement("input");
i.type = "text";
i.pattern = "[A-Z]{3}";
i.oninput = function() {
this.setCustomValidity('');
}
i.oninvalid = function() {
this.setCustomValidity("watch me break");
}
var s = document.createElement("input")
s.type = "submit";
f.appendChild(i);
f.appendChild(s)
document.getElementById("core").appendChild(f);
}
https://jsfiddle.net/oL07go4s/

innerHTML not showing up when added input element dynamically

I am trying to add an <input> element using Javascript. However, the innerHTML is not showing up. Below is my code:
function addElements()
{
container = document.getElementById("duration"); //a div container
var input1 = document.createElement("input");
var input2 = document.createElement("input");
input1.type = "number";
input1.min = "0";
input1.max = "10";
input1.required = true;
input1.innerHTML = "years";
input2.type = "number";
input2.min = "0";
input2.max = "12";
input2.required = true;
input2.innerHTML = "months";
container.appendChild(input1);
container.appendChild(input2);
}
The result of this code only produces two number input fields without the innerHTML. Is there anything wrong with my code?
Input elements don't have inner content you can set with innerHTML. Instead set value property:
input1.value = "years";
However, it seems that in your case you want to set placeholder:
input1.setAttribute("placeholder", "years");
or you can set corresponding property as well:
input1.placeholder = "years";
I think what you try to achieve is [label][input] in this case you have to add 2 new more elements on page.
function addElements()
{
container = document.getElementById("duration"); //a div container
var label1 = document.createElement("label");
var input1 = document.createElement("input");
var label2 = document.createElement("label");
var input2 = document.createElement("input");
input1.type = "number";
input1.min = "0";
input1.max = "10";
input1.required = true;
label1.innerHTML = "years";
input2.type = "number";
input2.min = "0";
input2.max = "12";
input2.required = true;
label2.innerHTML = "months";
container.appendChild(label1);
container.appendChild(input1);
container.appendChild(label2);
container.appendChild(input2);
}
addElements();
<div id="duration" />

Javascript created forms not appearing on the page

I've been tweaking my script, and it seems I've went off into the deep end. I'm trying to learn how to generate forms with Javascript, and it seems every time I think I've got it, I get to confident, add a little more, and mess something up. I can't spot the issue within the code. Please, any help would be appreciated.
Javascript: (form.js)
function initFirstLoad(){
var parentForm = document.getElementsByTagName('form')[0];
function addForm(){
var spawnForm = document.createElement("form");
spawnForm.setAttribute('name',"savefile");
spawnForm.setAttribute('method',"post");
spawnForm.setAttribute('action',"");
document.getElementsByTagName('body')[0].appendChild(spawnForm);
}
function addUniqueID(){
var characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
var stringLength = 10;
var randomString = '';
for (var i=0; i<stringLength; i++) {
var randomNumber = Math.floor(Math.random() * characters.length);
randomString += characters.substring(randomNumber,randomNumber+1);
}
var uniqueID = document.createElement("input");
uniqueID.setAttribute('type',"text");
uniqueID.setAttribute('name',"filename");
uniqueID.setAttribute('readonly',"readonly");
uniqueID.setAttribute('value',randomString);
parentForm.appendChild(uniqueID);
}
function addWeaponField(){
var weapsName = document.createElement("input");
weapsName.setAttribute('type',"text");
weapsName.setAttribute('name',"textdata[]");
var weapsNameQt = document.createElement("input");
weapsNameQt.setAttribute('type',"number");
weapsNameQt.setAttribute('name',"textdata[]");
weapsNameQt.setAttribute('value',"0");
parentForm.appendChild(weapsName);
parentForm.appendChild(weapsNameQt);
}
function addAmmoField(){
var ammoName = document.createElement("input");
ammoName.setAttribute('type',"text");
ammoName.setAttribute('name',"textdata[]");
var ammoNameQt = document.createElement("input");
ammoNameQt.setAttribute('type',"number");
ammoNameQt.setAttribute('name',"textdata[]");
ammoNameQt.setAttribute('value',"0");
parentForm.appendChild(ammoName);
parentForm.appendChild(ammoNameQt);
}
function addSubmitButton(){
var weapsNameSubmit = document.createElement("input");
weapsNameSubmit.setAttribute('type',"submit");
weapsNameSubmit.setAttribute('name',"submitsave");
weapsNameSubmit.setAttribute('value',"Done!");
}
}
window.addEventListener("load", initFirstLoad);
HTML: (form.htm)
<!DOCTYPE HTML>
<html>
<body style="background-color: rgb(225,225,225)">
<h3>Javascript Created Form and Fields</h3>
<script type="text/javascript" src="form.js"></script>
</body>
</html>
Am I doing something wrong? Is my syntax incorrect? Thank you in advance!
EDIT: Corrected addSubmitButton which was initially correct inside my code, but was accidentally removed. Thank you for the help guys, problem solved. I forgot to call functions the functions.
First of all your code is pretty weird structured (imo). If you are nesting functions to keep everything together then why you don't make a proper prototype-based "class" instead? that way you could make your code reusable. Let that aside you have a syntax error and you forgot to call your functions. Also you created a submit button but didn't add it to the form. In fact you didn't add a form to the dom at all. Here is a working demo with your issues fixed (however this code must be structured in a better way, but that's up to you:-):
working jsfiddle demo
function initFirstLoad(){
addForm();
var parentForm = document.getElementsByTagName('form')[0];
addUniqueID();
addWeaponField();
addAmmoField();
addSubmitButton();
function addForm(){
var spawnForm = document.createElement("form");
spawnForm.setAttribute('name',"savefile");
spawnForm.setAttribute('method',"post");
spawnForm.setAttribute('action',"");
document.getElementsByTagName('body')[0].appendChild(spawnForm);
}
function addUniqueID(){
var characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
var stringLength = 10;
var randomString = '';
for (var i=0; i<stringLength; i++) {
var randomNumber = Math.floor(Math.random() * characters.length);
randomString += characters.substring(randomNumber,randomNumber+1);
}
var uniqueID = document.createElement("input");
uniqueID.setAttribute('type',"text");
uniqueID.setAttribute('name',"filename");
uniqueID.setAttribute('readonly',"readonly");
uniqueID.setAttribute('value',randomString);
parentForm.appendChild(uniqueID);
}
function addWeaponField(){
var weapsName = document.createElement("input");
weapsName.setAttribute('type',"text");
weapsName.setAttribute('name',"textdata[]");
var weapsNameQt = document.createElement("input");
weapsNameQt.setAttribute('type',"number");
weapsNameQt.setAttribute('name',"textdata[]");
weapsNameQt.setAttribute('value',"0");
parentForm.appendChild(weapsName);
parentForm.appendChild(weapsNameQt);
}
function addAmmoField(){
var ammoName = document.createElement("input");
ammoName.setAttribute('type',"text");
ammoName.setAttribute('name',"textdata[]");
var ammoNameQt = document.createElement("input");
ammoNameQt.setAttribute('type',"number");
ammoNameQt.setAttribute('name',"textdata[]");
ammoNameQt.setAttribute('value',"0");
parentForm.appendChild(ammoName);
parentForm.appendChild(ammoNameQt);
}
function addSubmitButton(){
var weapsNameSubmit = document.createElement("input");
weapsNameSubmit.setAttribute('type',"submit");
weapsNameSubmit.setAttribute('name',"submitsave");
weapsNameSubmit.setAttribute('value',"Done!");
parentForm.appendChild(weapsNameSubmit);
}
}
window.addEventListener("load", initFirstLoad());
Not how i would build the form but correcting your method....
function initFirstLoad(){
var spawnForm = document.createElement("form");
spawnForm.setAttribute('name',"savefile");
spawnForm.setAttribute('method',"post");
spawnForm.setAttribute('action',"");
document.getElementsByTagName('body')[0].appendChild(spawnForm);
var parentForm = document.getElementsByTagName('form')[0];
var characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
var stringLength = 10;
var randomString = '';
for (var i=0; i<stringLength; i++) {
var randomNumber = Math.floor(Math.random() * characters.length);
randomString += characters.substring(randomNumber,randomNumber+1);
}
var uniqueID = document.createElement("input");
uniqueID.setAttribute('type',"text");
uniqueID.setAttribute('name',"filename");
uniqueID.setAttribute('readonly',"readonly");
uniqueID.setAttribute('value',randomString);
parentForm.appendChild(uniqueID);
var weapsName = document.createElement("input");
weapsName.setAttribute('type',"text");
weapsName.setAttribute('name',"textdata[]");
var weapsNameQt = document.createElement("input");
weapsNameQt.setAttribute('type',"number");
weapsNameQt.setAttribute('name',"textdata[]");
weapsNameQt.setAttribute('value',"0");
parentForm.appendChild(weapsName);
parentForm.appendChild(weapsNameQt);
var ammoName = document.createElement("input");
ammoName.setAttribute('type',"text");
ammoName.setAttribute('name',"textdata[]");
var ammoNameQt = document.createElement("input");
ammoNameQt.setAttribute('type',"number");
ammoNameQt.setAttribute('name',"textdata[]");
ammoNameQt.setAttribute('value',"0");
parentForm.appendChild(ammoName);
parentForm.appendChild(ammoNameQt);
var weapsNameSubmit = document.createElement("input");
weapsNameSubmit.setAttribute('type',"submit");
weapsNameSubmit.setAttribute('name',"submitsave");
weapsNameSubmit.setAttribute('value',"Done!");
}
window.addEventListener("load", initFirstLoad);
Your last line is window.addEventListener("load", initFirstLoad);. Change it to window.addEventListener("load", initFirstLoad()); and 'function addSubmitButton{ ' to 'function addSubmitButton(){',perhaps you might need to call you functions after declaring your parent form, if i am not wrong

Categories