Adding new form fields based on a number input - javascript

I'm trying to get this to work where when a user types in a number and it creates the corresponding number of input fields. I've tried with onclick and onchange and nothing seems to happen. Any idea what I'm missing?
var siblings = document.getElementById('siblings');
var value = siblings.value;
siblings.onchange = function(){
let i = 0;
do{
var newField = document.createElement('input');
newField.setAttribute('type','text');
newField.setAttribute('name','siblingInfo[]');
newField.setAttribute('class','siblingInfo');
newField.setAttribute('siz',50);
siblings.appendChild(newField);
i++
}
while (i < value);
}
<i>Do you have any siblings? </i>
<input type="number" id="siblings" name="siblings" min="0">

There are two points in your code needs to change:
let value = siblings.value; should be inside the onchange function
siblings.appendChild(newField); can change to siblings.appendChild(newField); since siblings is input type and can not append child
var siblings = document.getElementById('siblings');
siblings.onchange = function(){
let value = siblings.value;
let i = 0;
do{
var newField = document.createElement('input');
newField.setAttribute('type','text');
newField.setAttribute('name','siblingInfo[]');
newField.setAttribute('class','siblingInfo');
newField.setAttribute('siz',50);
// to make each element in one line we can add a br element before the newField
siblings.parentNode.appendChild(document.createElement('br'));
siblings.parentNode.appendChild(newField);
i++
}
while (i < value);
}
<div>
<i>Do you have any siblings? </i>
<input type="number" id="siblings" name="siblings" min="0">
</div>

Related

javascript appear a thing with specific id using appendChild

I don't know how to explain it, I don't want it to be unclear, so first thing first, I want to show this HTML code :
<body>
<form class="" action="index.html" method="post">
<input type="num" onkeyup="addOptions()" name="member" id="member">
<div id="selects">
</div>
</form>
</body>
And this is the javascript code :
<script type="text/javascript">
function addOptions() {
document.getElementById('selects').innerHTML = "";
var inputValue = document.getElementById('member').value;
for (var i = 0; i < inputValue; i++) {
var select = document.createElement('select');
var option = document.createElement('option');
option.innerText = "Example";
select.appendChild(option);
document.getElementById('selects').appendChild(select);
}
}
</script>
So, groove of this code will be if I type num in input num, the select will be appear as many as I type the num. But, it just will run the select option. So, my question is can I appear that the option is in HTML code? So when I type the num in the textfield, I will appear something like this for example :
<option value="example" id="example">example</option>
So the option code will be running as many as the num, like when I type 3 in the textfield, I will get 3 code like in above.
If I got it right, there are some issues in your code. I believe you are trying to achieve a drop down using select.
Inside for loop you creating select in each iteration which I think you don't want. To make value, id avilable to the newly created option you have to set those properties to the option.
Try the following:
function addOptions() {
document.getElementById('selects').innerHTML = "";
var select = document.createElement('select');
var inputValue = Number(document.getElementById('member').value);
for (var i = 0; i < inputValue; i++) {
var option = document.createElement('option');
option.innerText = "Example" + i;
option.value = "example" + i;
option.id = "example" + i;
select.append(option);
}
if(select.innerHTML) // if at least one option then append select
document.getElementById('selects').appendChild(select);
}
<input type="num" oninput="addOptions()" name="member" id="member"><br><br>
<div id="selects">
</div>
Just move some lines out of your for loop, as following:
function addOptions() {
document.getElementById('selects').innerHTML = "";
var inputValue = document.getElementById('member').value;
var select = document.createElement('select');
for (var i = 0; i < inputValue; i++) {
var option = document.createElement('option');
option.innerText = "Example "+i;
select.appendChild(option);
}
document.getElementById('selects').appendChild(select);
}
<form class="" action="index.html" method="post">
<input type="num" onkeyup="addOptions()" name="member" id="member">
<div id="selects">
</div>
</form>

Loop radio-button form javascript

I am trying to loop a radio-button form but with no success.
Despite the length of the form is 3 (same as number of radiobuttons) I can not access individual elements.
The purpose is to change the text. Its works If I want to access the first element:
var child = form.firstChild;
alert(child.nextSibling.nextSibling.nextSibling.innerHTML);
this returns the first radiobutton text.
But if I create a loop out of this
function getRadioBInfo() {
var form = document.getElementById("myform");
for (var i = 0; i < form.length; i++) {
var iForm = form[i];
var child = iForm.firstChild;
alert(child.nextSibling.nextSibling.nextSibling.innerHTML);
}
}
.. I get I TypeError: child is null
What is wrong with this code?
HTML
<form action="" name="deliver_form" id="myform" style="display: block;">
<input type="radio" name="delivering" id="radio1" value="deliver"> <label>label1</label><br>
<input type="radio" name="delivering" value="comeandtake"> <label>label2</label><br>
<input type="radio" name="delivering" value="express"> <label>label3</label>
</form>
I think you are looking for something like following.
var form = document.getElementById("myform");
for (var i = 0; i < form.length; i++) {
var child = form.getElementsByTagName('input')[i];
alert(child.nextSibling.nextSibling.innerHTML);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" name="deliver_form" id="myform" style="display: block;">
<input type="radio" name="delivering" id="radio1" value="deliver"> <label>label1</label><br>
<input type="radio" name="delivering" value="comeandtake"> <label>label2</label><br>
<input type="radio" name="delivering" value="express"> <label>label3</label>
</form>
Since you've tagged jquery, you could use:
$('[name=delivering']).each( function() {
alert( $(this).find('label').html() );
});
To get the label followed after the radio button you could try this:
function getRadioBInfo() {
var form = document.getElementById("myform");
var radios = form.querySelectorAll('input[type=radio]');
var i;
for (i = 0; i < radios.length; i++) {
var radio = radios[i];
console.log(radio.nextSibling.innerHTML);
}
}
getRadioBInfo();
pitfall: there shouldn't be whitespace between the radio or the button. Otherwise nextSibling returns text and not the label
demo
Why you are not getting by name
Try this
function getRadioBInfo() {
var arrRadioBtns = document.getElementsByName("delivering");
for (var i = 0; i < arrRadioBtns.length; i++) {
var btn = arrRadioBtns[i];
alert (btn.value);
}
}
Working Example
form[i] contains only radio buttons.If You want to take the labels Try using
var lbl = document.getElementsByTagName('label');
for (var i=0;i < lbl.length; i++){ lbl[i].innerHTML = 'radio' + i; }
and loop through the labels and change the text
Couple of observation
var form = document.getElementById("myform");
form will not be an array,Instead it will be a String,So you are iteration of the string.length;
You can use doucment.getElementsByName to get all radio buttons with common name
Hope this snippet will be useful
function getRadioBInfo() {
//Retun collection of radio button with same name
var _getRadio = document.getElementsByName("delivering");
// loop through the collection
for(var i = 0;i<_getRadio.length;i++){
//nextElementSibling will return label tag next to each radio input
console.log(_getRadio[i].nextElementSibling.innerHTML)
}
}
getRadioBInfo();
Jsfiddle

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!

Javascript getElementsByName() for changing names

I have a automatically rendered HTML form which uses a index for the input fields.
for quantity:
<input id="id_orderline_set-0-orderline_quantity" name="orderline_set-0-orderline_quantity" onkeyup="orderlineTotal()" type="number" value="120">
for product price;
<input id="id_orderline_set-0-orderline_product_price" name="orderline_set-0-orderline_product_price" onkeyup="orderlineTotal()" type="number" value="22">
for total line price;
<input id="id_orderline_set-0-orderline_total_price" name="orderline_set-0-orderline_total_price" tag="orderline_total_price" type="number" value="2640">
For the following lines the index of the id and name are increased, only quantity example shown;
<input id="id_orderline_set-1-orderline_quantity" name="orderline_set-1-orderline_quantity" onkeyup="orderlineTotal()" type="number" value="55">
I would like to use the following JavaScript to calculate the total line price;
function orderlineTotal()
{
var orderlineTotalPrice = 0;
var theForm = document.forms["orderform"];
var orderlineQuantityField = theForm.getElementsByName["orderline_quantity"];
var orderlineProductPriceField = theForm.getElementsByName["orderline_product_price"];
var orderlineTotalPriceField = theForm.getElementsByName["orderline_total_price"];
for (var i = 0; i < orderlineQuantityField.length; i ++) {
orderlineTotalPrice = orderlineQuantityField[i].value * orderlineProductPriceField[i].value;
orderlineTotalPriceField[i].value = orderlineTotalPrice;
}
}
Offcourse this wont work because the name of the elements do not match. Can i lookup the name of the element by using a partial name? If not, how should i loop through the input boxes to calculate the line total?
You tagged jQuery so if you want to use jQuery you can use ends with selector:
$("input[name$='orderline_quantity']")
ends with
there's also
starts with
$("input[name^='id_orderline_set-0']")
and contains
$("input[name*='orderline_']")
Maybe you could use static names. Set the equal input names for inputs of the same type and then use this function:
var elements = document.getElementsByName('name');
for (var i=0; i<elements.length; i++) {
doSomething(elements[i]);
}
where name matches name of input.
Example
Instead of:
name="orderline_set-0-orderline_total_price"
use:
name="orderline_total_price"
and then:
var orderlineTotalPriceField = theForm.getElementsByName["orderline_total_price"];
and so on...

Categories

Resources