Adding dom elements relative to input value - javascript

I have this function which add elements to the dom according to the value inserted into an input element, and if i insert new value in to the input the previous elements are erased and new elements are inserted.
what i want is to keep the old elements and add new ones to it
html:
<input type="text" placeholder="insert the number of div" class="number">
<button>submit</button>
<br>
<div id="wrapper"></div>
jquery:
$('button').click(function(){
var boxes = '';
var i;
var inputValue = $('.number').val();
for(i=0; i < inputValue; i++){
boxes += "<div class='box'></div>";
}
$('#wrapper').html(boxes);
});

Instead of $.html
$('#wrapper').html(boxes);
Use
$('#wrapper').append(boxes);
You can read more about both methods here:
append
html

Related

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!

How to retain a text in textfield

I have a link the purpose of the link is to add a textfield dynamically when i click it. But the problem is that if i have entered a text in the previous generated textfield and click on the link, textfield is generated but the page refresh and the input text resets.
html file
<script>
var countBox =3;
var boxName = 0;
function addInput()
{
var boxName="textBox"+countBox;
document.getElementById('responce').innerHTML+='<br /><input type="radio" name="choices" value="o'+countBox+'" id="o'+countBox+'"/><label>Option '+countBox+':</label> <input type="text" id="option'+countBox+'" name="option'+countBox+'"" placeholder="Enter here..." /><br/>';
countBox += 1;
}
</script>
<br />Add another(max.5)
How can i add the textfield and also retain the the text in the textfield. Hope you understood my problem
Thanks in advance.
The page is not refreshed, so that's not the problem. The problem is that you are using .innerHTML += to add the new elements. This is will destroy and recreate the existing elements: The elements are serialized to HTML, then you are concatenating the string to add new HTML and after the assignment the browser has to parse the HTML to create DOM Elements again. In this process all data will be lost.
Use DOM manipulation methods instead. I.e. create the elements with document.createElement and add them with Node.appendChild.
Using .innerHTML to override existing content or to initialize an element for the first time is OK. But using it to add elements to an existing element can lead to problems (as mentioned above) so it is better avoided in this case.
Example:
function addInput() {
var boxName="textBox"+countBox;
var input = document.createElement('input');
input.id = input.name = 'option'+countBox;
var parent = document.getElementById('responce');
parent.appendChild(document.createElement('br'));
parent.appendChild(input);
// create/add other elements...
countBox += 1;
}
Or a mix of both:
function addInput() {
var boxName="textBox"+countBox;
var container = document.createElement('div');
container.innerHTML = '<input type="radio" name="choices" value="o'+countBox+'" id="o'+countBox+'"/><label>Option '+countBox+':</label> <input type="text" id="option'+countBox+'" name="option'+countBox+'"" placeholder="Enter here..." />';
document.getElementById('responce').appendChild(container);
countBox += 1;
}

How to get the innerHTML of an input control including the values?

I have a div, its called tab1. Inside the tab1 div are many inputs (fields and radio buttons). I am getting the innerHTML like this:
document.getElementById("tab1").innerHTML;
Example code:
<div id="tab1">
<input type="text" id="text1" />
</div>
That works, but if I entered any value into a text1 input for example, its not in the innerHTML. How would I get the innerHTML including the entered values? Is that possible at all?
Thanks!
<div id="tab1">
<input type="text" id="text1"
onkeyup="javascript:this.setAttribute("value", this.value);"/>
</div>
This will gives the values with div's innerHTML.
document.getElementById("tab1").innerHTML;
You can change the event accordingly, I set it onKeyUp.
If you want to get the values of inputs/radios, you can do it with jQuery:
var Inputs = $("div#tab1 input, div#tab1 radio");
You now have an array of all input and radios in the variable Inputs. You can then access the values like this: Inputs[0].value
If you want to use plain JavaScript that could look like this:
var Inputs = document.getElementById("tab1").getElementsByTagName('input');
You can now access them like:Inputs[0].valueandRadios[0].value`
#edit
Thanks, I corrected these mistakes.
If you type something in the textbox, what does the innerHTML look like? Does it look like
<input type="text" id="text1" value="your_value" />?
If so, here is a simple function that returns what you want:
function getInnerHtml() {
var div = document.getElementById("tab1");
var childNodes = div.childNodes;
var innerHtml = "";
for (var i = 0; i < childNodes.length; i++) {
var node = childNodes[i];
if (node.nodeType == 1) {
if (node.getAttribute("type") == "text") {
if (node.value != "") {
//! This will change the original outerHTML of the textbox
//If you don't want to change it, you can get outerHTML first, and replace it with "value='your_value'"
node.setAttribute("value", node.value);
}
innerHtml += node.outerHTML;
} else if (node.getAttribute("type") == "radio") {
innerHtml += node.outerHTML;
}
}
}
}
Hope it's helpful.

Categories

Resources