Javascript 'innerHTML' Method Overwriting Checkbox Selection - javascript

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

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.

How to save the values in existing input fields when adding a new one?

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'))

Dynamically adding HTML form fields based on a number specified by the user [duplicate]

This question already has answers here:
Dynamically creating a specific number of input form elements
(2 answers)
Closed 1 year ago.
I've a form field named Number of messages, and based on what number the user specifies, I want the exact number of text fields to be dynamically generated below to allow users to enter specified number of messages.
I have browsed through some examples where JQuery is used to generate dynamic form fields, but since I'm not acquainted with JQuery, those examples are a bit too complex for me to grasp. I do know the basics of JavaScript, and would really appreciate if I could find a solution to my query using JavaScript.
function addinputFields(){
var number = document.getElementById("member").value;
for (i=0;i<number;i++){
var input = document.createElement("input");
input.type = "text";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
and html code will be
Number of members:<input type="text" id="member" name="member" value=""><br />
<button id="btn" onclick="addinputFields()">Button</button>
<div id="container"/>
fiddle here
You can try something similar to this...
var wrapper_div = document.getElementById('input_set');
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
var n = document.getElementById("no_of_fields").value;
var fieldset = document.createElement('div'),
newInput;
for (var k = 0; k < n; k++) {
newInput = document.createElement('input');
newInput.value = '';
newInput.type = 'text';
newInput.placeholder = "Textfield no. " + k;
fieldset.appendChild(newInput);
fieldset.appendChild(document.createElement('br'));
}
wrapper_div.insertBefore(fieldset, this);
}, false);
No. of textfields :
<input id="no_of_fields" type="text" />
<div id="input_set">
<p>
<label for="my_input"></label>
</p>
<button id="btn" href="#">Add</button>
</div>
It is a simple task which is made simpler with jQuery. You need to first get the value from the input field for which you can use .val() or .value. Once you get the value, check if it is an integer. Now, simply use .append() function to dynamically add the elements.
HTML
<form id="myForm">
Number of Messages: <input id="msgs" type="text"> </input>
<div id="addmsg">
</div>
</form>
JAVASCRIPT
$("#msgs").on('change', function()
{
var num = this.value;
if(Math.floor(num) == num && $.isNumeric(num))
{
$("#addmsg").text('');
for(var i = 0; i < num; i++)
{
$("#addmsg").append("<input type='text'/><br/>");
}
}
});
Fiddle
Note, everytime the value in the input changes, I am first clearing the div by:
$("#addmsg").text('');
And then I loop and keep adding the input field. I hope this helps!

Multiple dynamic input text javascript

Im having trouble creating multiple input texts with javascript.
My point is create a new input text everytime the input before is completed. (parent?)
Ive some code for comboboxs, but this time I need just input text box.
How can I do that ?
I've found this code:
<script type="text/javascript">
function addInput()
{
var x = document.getElementById("inputs");
x.innerHTML += "<input type=\"text\" />";
}
</script>
<input type="button" onmousedown="addInput();" />
<div id="inputs"></div>
But for my problem button is obsolete.
I think my event trigger will be something arround this "when user click in an input text box and it is != blank it creates a new one".
I migth need some ID to identify every input text box.
Cheers.
JSBIn Demo
Guess this helps:
<div id="myDiv">
<input type="text" id="txt_1" onkeydown="newTextBox(this)" />
</div>
<script type="text/javascript">
function newTextBox(element){
if(!element.value){
element.parentNode.removeChild( element.nextElementSibling);
return;
}
else if(element.nextElementSibling)
return;
var newTxt = element.cloneNode();
newTxt.id = 'txt_'+( parseInt( element.id.substring(element.id.indexOf('_')+1)) + 1);
newTxt.value='';
element.parentNode.appendChild(newTxt);
}
</script>
HTML code:
<div id="inputcontainer">
<input type="text" name="input0" id="input0" onkeyup="addInput();" />
</div>
And Javascript:
var currentindex = 0;
function addInput(){
var lastinput = document.getElementById('input'+currentindex);
if(lastinput.value != ''){
var container = document.getElementById('inputcontainer');
var newinput = document.createElement('input');
currentindex++;
newinput.type = "text";
newinput.name = 'input'+currentindex;
newinput.id = 'input'+currentindex;
newinput.onkeyup = addInput;
container.appendChild(newinput);
}
}
This will add a new input to the list only when the last input is not empty.
http://jsfiddle.net/HJbgS/
Have a look at the onchange event on your text input field. You can use it, like you use onmousedown on your button.
See http://www.w3schools.com/jsref/event_onchange.asp for an example.
In your addInput() function you should then check if the input of the previous textfield is != "".

Categories

Resources