Append Label and Div inside a Div using Javascript AppendChild - javascript

I'm trying to create a dynamic form where user can add more fields for additional inputs.
When user click this button:
<input style="font-size=12px; width:170px;" name="add" type="button" id="add" class='btn-style'/>
Additional set of forms will be shown in this area:
<div id="collegediv"></div>
Using this script:
document.getElementById('add').onclick = function () {
var collegediv = document.getElementById('collegediv'),
inputatt = "form-control input-sm",
firstdivatt = "form-group",
div = document.createElement('div');
div.setAttribute("class","col-sm-5");
var div2 = document.createElement('div');
div2.setAttribute("class","form-group");
var label = document.createElement('label');
label.setAttribute("class","col-sm-3 control-label input-sm");
var input = document.createElement('input');
collegediv.setAttribute("class",firstdivatt);
input.type = "text";
input.setAttribute("name", "college[]");
input.setAttribute("placeholder","Name of College/University");
input.setAttribute("class", inputatt);
div.appendChild(input);
div2.appendChild(label);
div2.appendChild(div);
collegediv.appendChild(div2);
};
The flow of the script is to
Append a textbox inside the div variable
Append a label inside the div2 variable
Append a div inside the div2 variable also
Then append the div2 inside the collegediv div
I'm also using bootstrap in the process, so the styling of <div> is like that.
My problem is that it doesn't format the way I think it should output.
Output/HTML SHOULD look like this:
<div id="collegediv">
<div class="form-group">
<label for="college" class="col-sm-3 control-label input-sm"></label>
<div class="col-sm-5">
<input type="text" name="college[]" class="form-control input-sm" placeholder="Name of College/University" required>
</div>
</div>
</div>
But this doesn't seem to be the output. My guess is that the appending of label and div inside the div2 is the problem. It's like they have conflict or overwriting the label with div once you append it also inside div2. Can anyone help me with this. Thanks.

This outputs EXACTLY what you said you wanted in your Output/HTML SHOULD look like this: section
document.getElementById('add').onclick = function () {
var collegediv = document.getElementById('collegediv');
// Make first div
var div_form_group = document.createElement('div');
div_form_group.setAttribute("class","form-group");
// Make label
var label = document.createElement('label');
label.setAttribute('for','college')
label.setAttribute('class','col-sm-3 control-label input-sm');
// Make inner div
var div_inner = document.createElement('div');
div_inner.setAttribute('class','col-sm-5');
// Make input
var input = document.createElement('input');
input.type = 'text';
input.setAttribute('name', 'college[]');
input.setAttribute('class', 'form-control input-sm');
input.setAttribute('placeholder','Name of College/University');
input.setAttribute('required','required');
// Attach elements
div_inner.appendChild( input );
div_form_group.appendChild( label );
div_form_group.appendChild( div_inner );
collegediv.appendChild( div_form_group );
};

Related

How to create textNode for radio button with JS?

I am trying to make a radio button with JavaScript. It's easy with HTML i.e <input type="radio" name="sType" value="m">MALE, so far with JS I'm able to create <input type="radio" name="sType" value="m"> but I don't know how to create MALE text Node for it. Also I want to append this form in 3rd div element of body with id='user_input' so what should be it's DOM navigation?
Here is my code:
document.getElementsById('user_input').childNodes[0].appendChild(f);
var f = document.createElement("form");
f.setAttribute("id", "myForm");
f.setAttribute('method',"post");
f.setAttribute('action',"ride_test.php");
var radio1 = document.createElement("input"); //input element, text
radio1.setAttribute("id","radio1");
radio1.setAttribute('type',"radio");
radio1.setAttribute('name',"sType");
radio1.setAttribute('value',"m");
f.appendChild(radio1);
If you want to add a description to the radio button, you should create a label and insert the description of the radio there.
let f = document.createElement("form");
let radio1 = document.createElement("input"); //input element, text
radio1.setAttribute("id","radio1");
radio1.setAttribute('type',"radio");
radio1.setAttribute('name',"sType");
radio1.setAttribute('value',"m");
let label = document.createElement('label');
label.textContent = "MALE";
f.appendChild(radio1);
f.appendChild(label);
document.body.appendChild(f)
You can also create a text node and append after input, but this is not recommended option:
//The same as above
let desc = document.createTextNode("MALE")
f.appendChild(radio1)
f.appendChild(desc);
document.body.appendChild(f)`
Fiddle: https://jsfiddle.net/dpu54as9/
Input tags are auto-enclosing tags and should not have any text. You need to use a label tag alongside (you can check this link), such as:
<input type="radio" name="sType" id="radio1" value="m"/>
<label for="radio1">MALE</label>
And to do so in your code, simply create a new label element, set its text and append to the form:
var f = document.createElement("form");
f.setAttribute("id", "myForm");
f.setAttribute('method',"post");
f.setAttribute('action',"ride_test.php");
var radio1 = document.createElement("input"); //input element, text
var label1 = document.createElement("label");
// link label to input through id
label1.setAttribute("for", "radio1");
label1.innerHTML = "MALE";
radio1.setAttribute("id","radio1");
radio1.setAttribute('type',"radio");
radio1.setAttribute('name',"sType");
radio1.setAttribute('value',"m");
f.appendChild(radio1);
f.appendChild(label1);
Note that the IDs are unique, meaning you can't have more than 1 id with the same name simultaneously on the DOM. The best way to achieve what you want is to change user_input to a class (which is not unique), and then append to DOM as follows:
document.body.getElementsByClassName('user_input')[2].appendChild(f);

Adding form post/submit button to javascript script

I found this code on here (thanks to Xavi López) and it is ideal for what I need to add to my project but I'm in need of some help adding a Form post and submit button in JavaScript. I have no knowledge on this subject and I've tried looking at some example but non of them seem to work. I would be grateful if someone could help me. After the user adds the relevant number of input boxes and adds there data, I would like to have a submit button which will POST the results to another web page (result page)
I have added the solution to the below coding (thank you MTCoster) but I'm now try to find a solution to having the submit button appear only when an entry has been added. I have tried different methods but non will work.
function addFields() {
// Number of inputs to create
var number = document.getElementById('member').value;
// Container <div> where dynamic content will be placed
var container = document.getElementById('container');
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++) {
// Append a node with a random text
container.appendChild(document.createTextNode('Member ' + (i + 1) + ' '));
// Create an <input> element, set its type and name attributes
var input = document.createElement('input');
input.type = 'text';
input.name = 'member' + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement('br'));
}
}
<input type="text" id="member" name="member" value="">Number of Pins: (max. 48)<br>
Add Pinout Entries
<form action="result.asp" method="POST">
<div id="container"></div>
<input type="submit" value="Add Data">
</form>
You’re almost there - all you need to do is wrap your inputs in a <form> element:
function addFields() {
// Number of inputs to create
var number = document.getElementById('member').value;
// Container <div> where dynamic content will be placed
var container = document.getElementById('container');
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++) {
// Append a node with a random text
container.appendChild(document.createTextNode('Member ' + (i + 1) + ' '));
// Create an <input> element, set its type and name attributes
var input = document.createElement('input');
input.type = 'text';
input.name = 'member' + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement('br'));
}
}
<input type="text" id="member" name="member" value="">Number of Pins: (max. 48)<br>
Add Pinout Entries
<form action="/url/to/post/to" method="POST">
<div id="container"></div>
<input type="submit">
</form>
If you’d like the submit button to only appear after at least one input is visible, you could add it at to div#container at the end of addFields(). I’ll leave this as an exercise to the OP, since it’s not much different to how you’re adding the input fields.

for each option create new elements and remove other if they exists

how onchange remove and add new elements? i want for each option create new elements and remove other if they exists, https://codepen.io/Datik/pen/Bddmrv
Each option has its own "list" of elements that needs to show on form
for example:
option Standard will show input type='text' only
option VIP will show input and select
Right now, its just create new elements when i choose option, tried checkin for childNodes.length, didn't help
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('select[name="productType"]').onchange=changeEventHandler;},false);
function changeEventHandler(event) {
var getSelect = document.getElementById('product');
var newInput = document.createElement('input');
var newSelect = document.createElement('select');
newInput.setAttribute('type','text');
newInput.setAttribute('placeholder','title');
if(event.target.value=='Standard'){
// if(getSelect.childNodes.length>0){
// getSelect.removeChild(newInput);
// }
getSelect.parentNode.appendChild(newInput);
}
else if(event.target.value=='VIP'){
getSelect.parentNode.appendChild(newInput);
getSelect.parentNode.appendChild(newSelect);
}
else{
getSelect.removeChild(newInput);//tried to delete 1 input if choose 1st option
}
}
You are trying to remove newInput element from getSelect element with this code:
getSelect.removeChild(newInput);
but your input and select are on the same dom level. Try this:
getSelect.parentNode.removeChild(newInput);
You can also symplify your code. Just add container for new fields and it will be easier to manipulate them. Here is working example:
html:
<div class="container">
<fieldset>
<select name="productType" id="product">
<option> </option>
<option>Standard</option>
<option>VIP</option>
</select>
</fieldset>
<div id="fields">
</div>
js:
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('select[name="productType"]').onchange=changeEventHandler;},false);
function changeEventHandler(event) {
//add container for product fields
var fieldsContainer = document.getElementById('fields');
//clean container
fieldsContainer.innerHTML = '';
var newInput = document.createElement('input');
newInput.setAttribute('type','text');
newInput.setAttribute('placeholder','title');
if(event.target.value=='Standard'){
fieldsContainer.appendChild(newInput);
}
else if(event.target.value=='VIP'){
var newSelect = document.createElement('select');
fieldsContainer.appendChild(newInput);
fieldsContainer.appendChild(newSelect);
}
}

Adding a label to a text area which was created using javascript

If This question has been answered please direct me to the answer
I am working on creating a mobile application which is a form designed based off a form which is used at my job. Part of this form will require the input of numbers which must fall within a specific range of numbers. If the numbers input fall outside that range of numbers, the user will need to input "corrective actions" at the end of the form.
I have a javascript function to "validate" these input fields. I have also been able to get the same function to generate a <textarea> in the correct location, but when I try to get the function to pull the content of the input field's label and add it to the generated text area the function does not work.
The following is a small portion of both the HTML form and the javascript associated with the input fields:
<div id="coldtemp" data-role="ui-content">
<label for="bottomair">Maketable Air Temp (bottom)</label>
<input data-clear-btn="true" name="bottomair" required id="bottomair" type="number" size="3" onChange="coldValidate(this)">
<p class="tollorance"></p>
</div>
<div id="correction">
</div>
The javascript:
function coldValidate(elem) {
var lable = document.createElement("label");
var child = elem.parentNode.getElementByTagName("label").textContent;
//lable.appendChild(child);
var para = document.createElement("textarea");
var element = document.getElementById("correction");
var x, text;
x = +elem.value;
if (isNaN(x) || x < 33 || x > 40) {
text = "Temp Out of Tolerance</p>";
} else {
text = " ";
}
elem.parentNode.nextElementSibling.innerHTML = text;
//element.appendChild(lable);
element.appendChild(para);
}
I have tried variations on the .getElementBy javascript method but nothing works and I am truly stumped. I have also commented out part of the "label" code in an attempt to figure out what was going wrong, this is why the lable.appendChild(child); and element.appendChild(lable); are both commented out.
The problem is that you are using getElementByTagName("label"), which is invalid syntax. What you're looking for is getElementsByTagName("label")[0]:
function coldValidate(elem) {
var lable = document.createElement("label");
var child = elem.parentNode.getElementsByTagName("label")[0].textContent;
//lable.appendChild(child);
var para = document.createElement("textarea");
var element = document.getElementById("correction");
var x, text;
x = +elem.value;
if (isNaN(x) || x < 33 || x > 40) {
text = "Temp Out of Tolerance</p>";
} else {
text = " ";
}
elem.parentNode.nextElementSibling.innerHTML = text;
//element.appendChild(lable);
element.appendChild(para);
}
<div id="coldtemp" data-role="ui-content">
<label for="bottomair">Maketable Air Temp (bottom)</label>
<input data-clear-btn="true" name="bottomair" required id="bottomair" type="number" size="3" onChange="coldValidate(this)">
<p class="tollorance"></p>
</div>
<div id="correction">
</div>
Hope this helps! :)
EDIT:
The additional problem that you're facing with the commented code is due to you attempting to set child variable as the textContent of the label element, and then append it to the label. Instead, you need to set the child variable as the label itself, and append it to element, rather than lable:
function coldValidate(elem) {
var lable = document.createElement("label");
var child = elem.parentNode.getElementsByTagName("label")[0];
var para = document.createElement("textarea");
para.setAttribute("id", "textbox");
child.setAttribute("for", "textbox");
var element = document.getElementById("correction");
var x, text;
x = +elem.value;
if (isNaN(x) || x < 33 || x > 40) {
text = "Temp Out of Tolerance</p>";
} else {
text = " ";
}
elem.parentNode.nextElementSibling.innerHTML = text;
element.appendChild(child);
element.appendChild(para);
}
<div id="coldtemp" data-role="ui-content">
<label for="bottomair">Maketable Air Temp (bottom)</label>
<input data-clear-btn="true" name="bottomair" required id="bottomair" type="number" size="3" onChange="coldValidate(this)">
<p class="tollorance"></p>
</div>
<div id="correction">
</div>
Note that I have also given the new textbox an ID, and given the label a new 'for' field, which correlates to the new textbox.
Hope this helps! :)

Javascript 'innerHTML' Method Overwriting Checkbox Selection

I have a form, id="myForm" or document.forms[0], with checkbox inputs, which I am writing dynamically with the help of Javascript functions and another HTML form, id="addForm" or document.forms[1], which has a text box and a clickable button.
The myForm is:
<form id="myForm" action="Save.php" method="post">
<div id="skillSet"></div>
<input type="submit">
</form>
My addForm is:
<form id="addForm"><input id="skillAdd" type="text" name="newSkillName">
<input class="button" type="button" value="Add" onClick="addSkill(document.forms[1].newSkillName.value)">
</form>
and my javascript function addSkill() is:
function addSkill(newSkill)
{
if(newSkill.length > 0)
{
var inner = document.getElementById("skillSet").innerHTML;
var newSkillDefinition = ('<div class="skillName"><label><input type="checkbox" checked name="skill[]" value="' + newSkill + '" title="Toggle Selection">' + newSkill + '</label></div>');
document.getElementById("skillSet").innerHTML = inner + newSkillDefinition;
}
}
All right, so I'll give you guys a scenario:
Using addForm, i've added 5 checkbox items to myForm, all 5 are checked by default of course, because of the checkbox "checked" attribute. But i decide to uncheck 3 of them. After this, I add another checkbox item. As soon as i do that, ALL of my previous checkbox items get checked automatically. So my previous selection has all vanished!
I know this definitely has something to do with the "checked" attribute and also innerHTML that I am using.
It's been a real headache. Is there any fix or way around this problem?
You can avoid that hassle by using the JavaScript appendChild method, instead of replacing the whole HTML. Something like that:
function addSkill(newSkill)
{
if(newSkill.length > 0)
{
var skillSet = document.getElementById("skillSet"),
skill = document.createElement('div'),
label = document.createElement('label'),
input = document.createElement('input');
input.type = "checkbox";
input.checked = "true";
input.name = "skill[]";
input.value = newSkill;
input.title = "Toggle Selection";
label.appendChild(input);
skill.appendChild(label);
skill.className = "skillName";
skillSet.appendChild(skill);
}
}
Add a node instead of using innerHTML:
var skillSet = document.getElementById("skillSet")
//Create elements
var div = document.createElement('div'),
var label = document.createElement('label');
var input = document.createElement('input');
var newSkill = "This is a new skill";
//Setup input
input.type = "checkbox";
input.checked = true;
input.name = "skill[]";
input.val = newSkill;
input.title = "Toggle Selection";
//Append new elements to div
var text = document.createTextNode(newSkill);
label.appendChild(text);
label.appendChild(input);
div.appendChild(label);
//Append div to original skillSet
skillSet.appendChild(div);
OUTPUT
<div>
<label>This is a new skill
<input type="checkbox" name="skill[]" title="Toggle Selection">
</label>
</div>
InnerHTML will "causes the destruction of all child elements, even if you're trying to append". Both of the solutions from raam86 and Rotem Harel should help you, as you should be using the appendChild method for this problem.
See this answer

Categories

Resources