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);
Related
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.
I'm trying to display the value of a text field onclick of the Search button.
On the search button, I'm using
onclick="document.getElementByid('output').innerHTML = this.value"
This gets the value of the Search button, which is just 'Search' and displays it in a 'output' div below.
Is there a way to use this to get the value of a separate text field once it is filled in by the user?
I've tried changing this.value to field1.value where field1 is the id/name of the text field, but this does not work.
Any help?
use
document.getElementByid('output').innerHTML = document.getElementById('field1').value
Try this (example):
var btn = document.getElementById('search');
var input = document.getElementById('field1');
var output = document.getElementById('output');
btn.addEventListener('click', function(e) {
output.innerHTML = input.value;
});
This is what my program's body looks like:
<form id = "input">
<input id = "0" >
</form>
<p onclick = "add()"> Add Another</p>
And on clicking the above The following function is executed:
var inputArea = document.getElementById("input");
next = 1;
function add(){
inputArea.innerHTML+= " <input id = " + next+ ">" ;
Where next is the id of new input field. In this case, since 0 already exists so value of next is 1.
One problem that I am encountering with this is that after adding a new input field, the values in all existing input fields are lost. How to save these values? My attempt is to place this code in function add():
for (i=0;i<next;i++)
{inputs[i] = document.getElementById(i);
inputV[i]= inputs[i].value;
inputs[i].value = inputV[i];}
But this does not works..
var inputArea = document.getElementById("input");
next = 1;
function add(){
inputArea.innerHTML+= " <input id = " + next+ ">" ;
var inputs = new Array();
var inputV = new Array();
for (i=0;i<next;i++)
{inputs[i] = document.getElementById(i);
inputV[i]= inputs[i].value;
inputs[i].value = inputV[i];}
next++;
}
<form id = "input">
<input id = "0" >
</form>
<p onclick = "add()"> Add Another</p>
You may want to dynamically add elements to your DOM tree like so
function add() {
var form = document.getElementById("input");
var input = document.createElement("input");
form.appendChild(input);
}
The problem with what you're doing is that when you write inside an input field, the changes are not represented in the HTML code, only in the memory of the browser. Thus if you add text through to code to form.innerHTML, the browser is going to reinterpret the text inside the form which will be
<input id="0"> <input id="1"> ...
and this will result in two empty input of type text being displayed.
Edit: you can then add your id tag via
function add() {
var form = document.getElementById("input");
var input = document.createElement("input");
input.id = someValue;
form.appendChild(input);
}
N.B. please indent your code in a somewhat logical manner.
The reason this is happening is that the dom, or more specifically inputArea's innerHtml doesnt get changed when you type into a form field. And what youre doing is resetting the innerHTML with a blank input BEFORE youre capturing the values.
so whats going on is you have HTML like this:
<input id='0' />
then type into the form so that it behaves like:
<input id='0' value='foo' />
but thats not what the innerHTML actual is. its still <input id='0' /> because the value is kept in memory not on the dom.
if you want to add new elements to the form, you need to use appendChild instead
so convert
inputArea.innerHTML+= " <input id = " + next+ ">"
to
inputArea.appendChild(document.createElement('input'))
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 );
};
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