Javascript created forms not appearing on the page - javascript

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

Related

Extra <br/>s are appearing even when I remove them by looping and removeChild()

As the title states, I can't seem to find the suspect for this behaviour.
Here's my script:
function myFunction() {
var marriedInputs = document.getElementById("marriedInputs");
var status = document.getElementById("maritalStatusList").value;
if (status == "Married") {
var breaks = marriedInputs.getElementsByTagName("BR");
for (var i = 0; i < breaks.length; i++) {
marriedInputs.removeChild(breaks[i]);
}
var spouseLabel = document.createElement("LABEL");
spouseLabel.setAttribute("id", "spouseLabelID");
spouseLabel.for = document.getElementById("spouseLname");
var spouseLabelText = document.createTextNode("SPOUSE: ");
spouseLabel.appendChild(spouseLabelText);
var spouseLnameInput = document.createElement("INPUT");
spouseLnameInput.setAttribute("id","spouseLname");
spouseLnameInput.setAttribute("type","text");
spouseLnameInput.setAttribute("name","spouseLastName");
spouseLnameInput.setAttribute("placeholder","Last Name");
var spouseFnameInput = document.createElement("INPUT");
spouseFnameInput.setAttribute("id","spouseFname");
spouseFnameInput.setAttribute("type","text");
spouseLnameInput.setAttribute("name","spouseFirstName");
spouseFnameInput.setAttribute("placeholder","First Name");
var spouseMnameInput = document.createElement("INPUT");
spouseMnameInput.setAttribute("id","spouseMname");
spouseMnameInput.setAttribute("type","text");
spouseLnameInput.setAttribute("name","spouseMiddleName");
spouseMnameInput.setAttribute("placeholder","Middle Name");
var childrenNumInput = document.createElement("INPUT");
childrenNumInput.setAttribute("id","childrenNum");
childrenNumInput.setAttribute("type","text");
childrenNumInput.setAttribute("name","numOfChildren");
childrenNumInput.setAttribute("placeholder","Number of Children");
childrenNumInput.setAttribute("onkeypress","return isNumberKey(event)");
var contactNumInput = document.createElement("INPUT");
contactNumInput.setAttribute("id","contactNum");
contactNumInput.setAttribute("type","text");
contactNumInput.setAttribute("name","spouseContactNo");
contactNumInput.setAttribute("placeholder","Contact Number");
contactNumInput.setAttribute("onkeypress","return isNumberKey(event)");
var addressInput = document.createElement("INPUT");
addressInput.setAttribute("id","address");
addressInput.setAttribute("type","text");
addressInput.setAttribute("name","spouseAddress");
addressInput.setAttribute("placeholder","Address");
marriedInputs.appendChild(spouseLabel);
marriedInputs.appendChild(document.createElement("BR"));
marriedInputs.appendChild(spouseLnameInput);
marriedInputs.appendChild(document.createElement("BR"));
marriedInputs.appendChild(spouseFnameInput);
marriedInputs.appendChild(document.createElement("BR"));
marriedInputs.appendChild(spouseMnameInput);
marriedInputs.appendChild(document.createElement("BR"));
marriedInputs.appendChild(childrenNumInput);
marriedInputs.appendChild(document.createElement("BR"));
marriedInputs.appendChild(contactNumInput);
marriedInputs.appendChild(document.createElement("BR"));
marriedInputs.appendChild(addressInput);
marriedInputs.appendChild(document.createElement("BR"));
document.getElementById("spouseLname").required = true;
document.getElementById("spouseFname").required = true;
document.getElementById("spouseMname").required = true;
document.getElementById("childrenNum").required = true;
document.getElementById("contactNum").required = true;
document.getElementById("address").required = true;
} else {
if (document.body.contains(document.getElementById("spouseLname"))) {
var breaks = marriedInputs.getElementsByTagName("BR");
for (var i = 0; i < breaks.length; i++) {
marriedInputs.removeChild(breaks[i]);
}
marriedInputs.removeChild(document.getElementById("spouseLabelID"));
marriedInputs.removeChild(document.getElementById("spouseLname"));
marriedInputs.removeChild(document.getElementById("spouseFname"));
marriedInputs.removeChild(document.getElementById("spouseMname"));
marriedInputs.removeChild(document.getElementById("childrenNum"));
marriedInputs.removeChild(document.getElementById("contactNum"));
marriedInputs.removeChild(document.getElementById("address"));
}
}
}
Can anyone pinpoint the problem? I'm not really a js person, I just needed this for some onchange in a select element.
And I would very appreciate any tips for writing a cleaner version of this script. Cheers!!
Forgot the HTML:
Marital Status:
<select id="maritalStatusList" onchange="myFunction()">
<option value="Single">Single
<option value="Married">Married
<option value="Divorced">Divorced
<option value="Widowed">Widowed
</select>
<div id="marriedInputs">
</div>
There were some issues in fetching brs and removing them. I tried replacing it with querySelector and it worked fine.
function removeBRs() {
var breaks = document.querySelectorAll('#marriedInputs br')
for (var i = 0; i < breaks.length; i++) {
marriedInputs.removeChild(breaks[i]);
}
}
JSFiddle.
Also a side note, there is a lot of redundant code. Export them into smaller functions with common logic. Also, you can wrap all fields for married case inside a container div and append this div to main #marriedInputs. This will ease process of removing it.
Following is the updated JSFiddle. I'd still recommend using wrapper div instead of br though. Also I have removed the use of removeBRs and deleted it.
Hope it helps!
I suggest writing this function in a different way:
function toggleMarriedInputs() {
var status = document.getElementById("maritalStatusList").value;
if (status == "Married") {
var container = document.createElement("div");
container.setAttribute("id", "marriedInputs");
// creating inputs and appending them to #marriedInputs
// appending #marriedInputs in target place
} else {
var marriedInputs = document.getElementById("marriedInputs");
marriedInput.parentNode.removeChild(marriedInputs);
}

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/

Creating an object with 4 button on javascript

I created an object on js with 4 buttons, but it's not showing,
this is my code:
function Keyboard() {
this.plus = document.createElement("input");
this.plus.type = "submit";
this.plus.value = "A";
this.minus = document.createElement("input");
this.minus.type = "submit";
this.minus.value = "B";
this.multi = document.createElement("input");
this.multi.type = "submit";
this.multi.value = "C";
this.divide = document.createElement("input");
this.divide.type = "submit";
this.divide.value = "D";
}
var k = new Keyboard();
document.body.appendChild(k);
I will add the onClick later, but why is this not showing?
Thanks!
Your Keyboard constructs a simple JavaScript object with 4 properties, but not a DOM object. Later, you try to append a simple JavaScript object to your document.
First, you need to create DOM element using document.createElement.
Second, you don't need new keyword here at all.
Third, you don't need to set subitems as properties. You append them to a parent object, and it is enough.
Try the following code:
function CreateKeyboard() {
var t = document.createElement("div");
var plus = document.createElement("input");
plus.type = "submit";
plus.value = "A";
t.appendChild(plus);
var minus = document.createElement("input");
minus.type = "submit";
minus.value = "B";
t.appendChild(minus);
var multi = document.createElement("input");
multi.type = "submit";
multi.value = "C";
t.appendChild(multi);
var divide = document.createElement("input");
divide.type = "submit";
divide.value = "D";
t.appendChild(divide);
return t;
}
document.body.appendChild(CreateKeyboard());
By the way, you can avoid code repetition. For example, by utilizing Array.prototype.forEach:
function CreateKeyboard() {
var t = document.createElement("div");
['A', 'B', 'C', 'D'].forEach(function(l) {
var elem = document.createElement("input");
elem.type = "submit";
elem.value = l;
t.appendChild(elem);
});
return t;
}
document.body.appendChild(CreateKeyboard());
This should work:
<script type="text/javascript">
function createSubmitButton(val) {
var el = document.createElement("input");
el.type = "submit";
el.value = val;
document.body.appendChild(el);
}
createSubmitButton("A");
createSubmitButton("B");
createSubmitButton("C");
createSubmitButton("D");
</script>
Make sure you place the script tag at the bottom of the html code, right before the ending body tag.
k is not type of Node. Append only Node elements you have created.
var k = new Keyboard();
document.body.appendChild(k.plus);
document.body.appendChild(k.minus);
document.body.appendChild(k.multi);
document.body.appendChild(k.divide);

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

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.

Categories