Multiple input fields using JS - javascript

Got the following JS code:
<script language="javascript">
fields = 0;
pNR = 0;
err = 0;
function addInput() {
if (fields != 40) {
document.getElementById('text').innerHTML += "<input type='text' name='first" + pNR + "' value='' /><input type='text' name='second" + pNR + "' value='' /><br />";
fields += 1;
pNR += 1;
} else {
if (err == 0) {
document.getElementById('text').innerHTML += "<br />Adaugati maxim 40 ingrediente.";
err = 1;
}
document.form.add.disabled = true;
}
}
</script>
and the following HTML:
<input name="name" style="color:#ffffff;" class="name required" type="button" onclick="addInput()" value="Add" />
<div id="text">
</div>
By default, there are no fields. When I press the Add button (fields are added two by two with different names), fill in the fields and click again the Add button, the filled fields are emptied. What did I do wrong?

You aren't simply adding new inputs.
You are:
converting the existing ones to HTML (the value attribute is unchanged, it will still have the default value, not the current value)
adding the HTML for the new inputs to it
generating new DOM elements from that HTML.
Don't use innerHTML. Use createElement, appendChild and friends.
This:
document.getElementById('text').innerHTML += "<input type='text' name='first" + pNR + "' value='' /><input type='text' name='second" + pNR + "' value='' /><br />";
Becomes this:
var firstInput = document.createElement("input");
var secondInput = document.createElement("input");
firstInput.type = secondInput.type = "text";
firstInput.name = "first" + pNR;
secondInput.name = "second" + pNR;
var text = document.getElementById("text");
text.appendChild(firstInput);
text.appendChild(secondInput);
text.appendChild(document.createElement("br"));
And, for the else case:
var text = document.getElementById("text");
text.appendChild(document.createElement("br"))
text.appendChild(document.createTextNode("Adaugati maxim 40 ingrediente."));
Working example: http://jsbin.com/OqIWeMum/2/edit

Related

how to get the text of an html input generated by javascript?

I'm having a problem I'm using a numeric keypad that I found in codepen this one
https://codepen.io/matthewfortier/pen/ENJjqR
my objective is to store the generated pin in a database but it's a little difficult to do that because I'm taking the generated pin to an input but it looks like this
<input hidden="" id="pin" value="" name="pin">9345</input>
how do i get this generated pin and save it in database
the code is the same as the link
In your html you have this:
<input type="hidden" id="pin" value="9345" name="pin" />
In your Javascript you have this:
let value = document.getElementById('pin').value;
console.log(value);
$(function() {
var container = $(".numpad");
var inputCount = 6;
// Generate the input boxes
// Generates the input container
container.append("<div class='inputBoxes' id='in'></div>");
var inputBoxes = $(".inputBoxes");
inputBoxes.append("<form class='led' class='form-group' action='cadastro.php' method='post'></form>");
var led = $(".led");
// Generates the boxes
for(var i = 1; i < inputCount + 1; i++){
led.append("<input type='password' maxlength=1 class='inp' id='" + i + "' />");
}
led.append("<input type='password' maxlength=12 name='numero' value='93445566' id='numero' />");
led.append("<input type='text' name='te' id='te' placeholder='' />");
led.append("<button id='btn1' type='submit' onclick=''>enviar</button>");
container.append("<div class='numbers' id='inb'><p id='textoo'><span class='bolded'>PIN</span> do serviço MULTICAIXA</p></div>")
var numbers = $(".numbers");
// Generate the numbers
for(var i = 1; i <= 9; i++){
numbers.append("<button class='number' type='button' name='" + i + "' onclick='addNumber(this)'><span class='pin_font'>" + i + "</span></button>");
}
addNumber = function take(field,vall) {
if (!$("#1").val())
{
$("#1").val(field.name).addClass("dot");
}
else if (!$("#2").val())
{
$("#2").val(field.name).addClass("dot");
}
else if (!$("#3").val())
{
$("#3").val(field.name).addClass("dot");
}
else if (!$("#4").val())
{
$("#4").val(field.name).addClass("dot");
}
else if (!$("#5").val())
{
$("#5").val(field.name).addClass("dot");
}
else if (!$("#6").val())
{
$("#6").val(field.name).addClass("dot");
vall = $("#1").val() + $("#2").val() + $("#3").val() + $("#4").val()+ $("#5").val()+ $("#6").val();
document.getElementById("pini").innerHTML = vall;
}
}

how to get array values, on input field

So I have multiple table data insert I want to get input value on some field so I can calculate on another field. How can I do that if that is an array field?
I've tried using javascript but it's only working on first field (not array field).
function tot() {
var txtFirstNumberValue = document.getElementById('price').value;
var txtSecondNumberValue = document.getElementById('qty').value;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
}
$(document).ready(function(){
$("#btn-add-form").click(function(){
var addi = parseInt($("#addi-form").val());
var nextform = addi + 1;
$("#insert-form").append("<b>Item Price " + nextform + " :</b>" +
"<input type='text' name='names[]' required>"
"<input id='price' type='text' name='price[]' onkeyup='tot();' required>"
"<input id='qty' type='text' name='qty[]' onkeyup='tot();' required>"
"<input type='text' name='total[]' required>"
$("#addi-form").val(nextform);
});
$("#btn-reset-form").click(function(){
$("#insert-form").html("");
$("#addi-form").val("1");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="btn-add-form">Add</button>
<button type="button" id="btn-reset-form">Reset</button><br><input type="text" name="names[]" required>
<input id="price" type="text" name="price[]" onkeyup="tot();" required>
<input id="qty" type="text" name="qty[]" onkeyup="tot();" required>
<input id="total" type="text" name="total[]" required>
<div id="insert-form"></div>
I expect that way works on added array table but it's not, it only affects field on my first table.
You can not assign the same ID to multiple DOM elements on the same page. I have updated your code a bit to use the item number with the ID. Like, for item 1 ID is price, for item 2 ID is price-2, for item 3 ID is price-3 and so on. Same done with qty and total.
You may try this code:
function sum_total() {
var totalSum = 0;
var calcTotalSum = document.getElementsByClassName("calc-total");
var totalItems = calcTotalSum.length;
var i = 0;
while(i < totalItems) {
if (calcTotalSum[i].value !== "") {
totalSum = totalSum + parseInt(calcTotalSum[i].value);
}
i += 1;
}
if(totalSum > 0) {
console.log("Total Sum is: ", totalSum);
}
}
function tot(event) {
var itemNo = event.target.getAttribute("data-item");
var txtFirstNumberValue = "";
var txtSecondNumberValue = "";
if (itemNo) {
txtFirstNumberValue = document.getElementById('price-' + itemNo).value;
txtSecondNumberValue = document.getElementById('qty-' + itemNo).value;
} else {
txtFirstNumberValue = document.getElementById('price').value;
txtSecondNumberValue = document.getElementById('qty').value;
}
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
if (itemNo) {
document.getElementById('total-' + itemNo).value = result;
} else {
document.getElementById('total').value = result;
}
}
sum_total();
}
$(document).ready(function(){
$("#btn-add-form").click(function(){
var addi = parseInt($("#addi-form").val());
var nextform = addi + 1;
$("#insert-form").append("<b>Item Price " + nextform + " :</b>" +
"<input type='text' name='names[]' required>" +
"<input id='price-" + nextform + "' data-item='" + nextform + "' type='text' name='price[]' onkeyup='tot(event);' required>" +
"<input id='qty-" + nextform + "' data-item='" + nextform + "' type='text' name='qty[]' onkeyup='tot(event);' required>" +
"<input id='total-" + nextform + "' class='calc-total' type='text' name='total[]' required>"
);
$("#addi-form").val(nextform);
});
$("#btn-reset-form").click(function(){
$("#insert-form").html("");
$("#addi-form").val("1");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="btn-add-form">Add</button>
<button type="button" id="btn-reset-form">Reset</button><br>
<input type="hidden" name="addi-form" id="addi-form" value=1 required>
<input type="text" name="names[]" required>
<input id="price" type="text" name="price[]" onkeyup="tot(event);" required>
<input id="qty" type="text" name="qty[]" onkeyup="tot(event);" required>
<input id="total" class="calc-total" type="text" name="total[]" required>
<div id="insert-form"></div>
Hope, it helps you.
EDITED: sum_total function to calculate the sum of the total amount.
I presume that you want to trigger the tot() function on the newly added table rows. For that purpose you need to:
call tot() function to bind to the newly added elements after they have been appended. Or use the jQuery bind method.
Use .class in place of #id attributes on the elemnts so that you can iterate through all of them using the class selector

Remove Form Field With Javascript

So I Have Looked Through The Site Only To Not Find The Answer For My Particular Problem. I Am Pretty New To Writing Code And Am Trying To Figure Out How To Remove A Form Field After Its Been Added with Javascript. Here is the code. I would Greatly Appreciate Feedback/Solutions.
var counter = 1;
var limit = 1000;
function addInput(Favorites){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<br>Favorite " + (counter + 1) + "<input type='text' name='Favorites[]'><input type ='button' value ='Remove'>";
document.getElementById(Favorites).appendChild(newdiv);
counter++;
}
function removeInput(newdiv){
document.getElementById('Favorites').removeChild(newdiv);
counter - 1;
}
}
<form>
<div id="Favorites">
Favorite 1<input type="text" name="Favorites[]">
</div>
<input type="button" value="Add New Favorite" onClick="addInput('Favorites');">
<input type = "button" value = "Save Changes">
</form>
there are various issues in your code so I have modified it a bit. So use following js code
var counter = 1;
var limit = 1000;
function addInput(){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = " <div class='inputElement'>Favorite " + (counter + 1) + "<input type='text' name='Favorites[]'><input type ='button' value ='Remove' onClick='removeInput(this)'></div>";
document.getElementById("Favorites").appendChild(newdiv);
counter++;
}
}
function removeInput(removeLink){
var inputElement = removeLink.parentNode;
inputElement.remove();
counter= counter - 1;
}
In html you can modify your code a bit
<form>
<div id="Favorites">
<div class='inputElement'>
Favorite 1<input type="text" name="Favorites[]">
</div>
</div>
<input type="button" value="Add New Favorite" onClick="addInput();">
<input type = "button" value = "Save Changes">
</form>
Check out above code here
https://jsbin.com/hizimateri/1/edit?html,js,console,output
If you have any issues with it . Let me know.
Maybe this help? Check the link here link
var counter = 1;
var limit = 2;
function addInput(Favorites) {
if (counter == limit) {
removeInput();
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<br>Favorite " + (counter + 1) + "<input type='text' name='Favorites[]'><input type ='button' value ='Remove'>";
document.getElementById(Favorites).appendChild(newdiv);
counter++;
}
function removeInput() {
var x = document.querySelector('#Favorites div:last-child');
x.remove();
--counter;
}
}

Counting form fields using js

I have the form that looks like this:
<form method="post" action="">
<label for="id_count-count">Count:</label>
<input id="id_count-count" type="number" name="count-count">
<div class="extrafieldWrapper"></div>
<input type="submit" value="Submit">
</form>
Depending on number of field count i add or delete new couple of fields item and item2. For example: if value of field count will be 2, it will generate two couples of fields item and item2.
There is this fields:
<label for="id_items-0-item">Item:</label>
<input id="id_items-0-item" type="number" name="items-0-item">
<label for="id_items-0-item2">Item2:</label>
<input id="id_items-0-item2" class="children_age" type="number" name="items-0-item2" value="0">
<div class="extrafieldWrapperChAge"></div>
Then, depending on each value of field item2 i add new fields that calls childrenage. There is how looks childrenage field:
<label for="id_childrenage-0-childrenage">ChildrenAge 1</label>
<input id="id_childrenage-0-childrenage" type="number" name="childrenage-0-childrenage" value="0">
Here is fiddle link .
And here is imgur of what i want and what i've got link.
Depending of value of item2 the id of childrenage is changing too. For example if i have '3' as value of item2, then i have id_childrenage-0-childrenage, id_childrenage-1-childrenage and id_childrenage-2-childrenage. And if i have several item2 i have new examples of childrenage that count their id from the start for each item2:
<label for="id_items-0-item2">Item2:</label>
<input id="id_items-0-item2" class="children_age" type="number" name="items-0-item2" value="2">
<div class="extrafieldWrapperChAge">
<label for="id_childrenage-0-childrenage">ChildrenAge</label>
<input id="id_childrenage-0-childrenage" type="number" name="childrenage-0-childrenage" value="0">
<label for="id_childrenage-1-childrenage">ChildrenAge</label>
<input id="id_childrenage-1-childrenage" type="number" name="childrenage-1-childrenage" value="0">
</div>
<label for="id_items-0-item2">Item2:</label>
<input id="id_items-0-item2" class="children_age" type="number" name="items-0-item2" value="1">
<div class="extrafieldWrapperChAge">
<label for="id_childrenage-0-childrenage">ChildrenAge</label>
<input id="id_childrenage-0-childrenage" type="number" name="childrenage-0-childrenage" value="0">
</div>
In example above i have 2 fields item2, on one of it value '2' and on another value '1'. According to this i have two fields of childrenage for the first item2 with id id_childrenage-0-childrenage and id_childrenage-1-childrenage, and one field childrenage for the second with id id_childrenage-0-childrenage. But i need that count of id childrenage go on from the first item2 to the last, this is example:
<label for="id_items-0-item2">Item2:</label>
<input id="id_items-0-item2" class="children_age" type="number" name="items-0-item2" value="2">
<div class="extrafieldWrapperChAge">
<label for="id_childrenage-0-childrenage">ChildrenAge</label>
<input id="id_childrenage-0-childrenage" type="number" name="childrenage-0-childrenage" value="0">
<label for="id_childrenage-1-childrenage">ChildrenAge</label>
<input id="id_childrenage-1-childrenage" type="number" name="childrenage-1-childrenage" value="0">
</div>
<label for="id_items-0-item2">Item2:</label>
<input id="id_items-0-item2" class="children_age" type="number" name="items-0-item2" value="1">
<div class="extrafieldWrapperChAge">
<label for="id_childrenage-2-childrenage">ChildrenAge</label>
<input id="id_childrenage-2-childrenage" type="number" name="childrenage-2-childrenage" value="0">
</div>
Here is js code that realize this:
$(function(){
$('#id_count-count').on('change', function(e){
var n = $('#id_count-count').val() || 0;
var html = "<input id='id_items-TOTAL_FORMS' type='hidden' value='" + n + "' name='items-TOTAL_FORMS'>"
+ "<input id='id_items-INITIAL_FORMS' type='hidden' value='0' name='items-INITIAL_FORMS'>"
+ "<input id='id_items-MIN_NUM_FORMS' type='hidden' value='0' name='items-MIN_NUM_FORMS'>"
+ "<input id='id_items-MAX_NUM_FORMS' type='hidden' value='15' name='items-MAX_NUM_FORMS'>";
for (var i = 0; i < n; i++) {
html += "<div>Items" + (i + 1) + "</div>"
+ "<br/><label for='id_items-" + i + "-item'>Item:</label>"
+ "<input id='id_items-" + i + "-item' type='number' name='items-" + i + "-item'/>"
+ "<label for='id_items-" + i + "-item2'>Item2:</label>"
+ "<input id='id_items-" + i + "-item2' type='number' value='0' name='items-" + i + "-item2' class='children_age'/>"
+ "<div class='extrafieldWrapperChAge'></div>";
}
$(".extrafieldWrapper").html(html);
});
$(".extrafieldWrapper").on('change', '.children_age', function(e){
var n = $(this).val() || 0;
var html = "<input id='id_childrenage-TOTAL_FORMS' type='hidden' value='" + n + "' name='childrenage-TOTAL_FORMS'>"
+ "<input id='id_childrenage-INITIAL_FORMS' type='hidden' value='0' name='childrenage-INITIAL_FORMS'>"
+ "<input id='id_childrenage-MIN_NUM_FORMS' type='hidden' value='0' name='childrenage-MIN_NUM_FORMS'>"
+ "<input id='id_childrenage-MAX_NUM_FORMS' type='hidden' value='15' name='childrenage-MAX_NUM_FORMS'>";
for (var i = 0; i < n; i++) {
html += "<br/><label for='id_childrenage-" + i + "-childrenage'>ChildrenAge "+(i+1)+"</label>"
+ "<input id='id_childrenage-" + i + "-childrenage' type='number' value='0' name='childrenage-" + i + "-childrenage' />";
}
$(this).next('.extrafieldWrapperChAge').html(html);
});
});
Hope you you understand what i mean.
I am newbie in java-script, can you help me to write the code in the right way. Thanks a lot!
This particular answer was getting needlessly long, so I've decided to truncate it to just the current answer.
The Code
$(function() {
var fieldset = $('<fieldset>');
var legend = $('<legend>');
var input = $('<input>').prop('type', 'number');
var hidden = $('<input>').prop('type', 'hidden');
var label = $('<label>');
var child_wrapper = $('<div class="child-wrapper">');
/*
Here we create a couple of new HTML elements. These elements are not a part of the
HTML DOM yet and can therefore be manipulated without any visual changes.
*/
var create_hidden_fields = function(str, fields_arr) {
var ret = [];
//return array;
$.each(fields_arr, function(i, obj) {
//Loops through each field to set up the hidden values
var h = hidden.clone();
//Clones the hidden fields
h.prop('id', 'id_' + str + '-' + obj.name).prop('name', str + '-' + obj.name).val(obj.value);
//Sets the ID, name, and value.
ret.push(h);
});
return ret;
};
$('#id_count-count').on('change', function(e) {
var n = $(this).val() || 0;
//Gets the id count value, or 0;
var hidden_fields = [{
name: 'TOTAL_FORMS',
value: n
}, {
name: 'INITIAL_FORMS',
value: 0
}, {
name: 'MIN_NUM_FORMS',
value: 0
}, {
name: 'MAX_NUM_FORMS',
value: 15
}];
//Hidden fields pre-build, makes life easier, since there seems to be a pattern
var h_arr = create_hidden_fields('items', hidden_fields);
//Hidden Array created
if ($(this.form).children(':hidden')) {
$(this.form).children(':hidden').remove();
//Removes all the current hidden fields, because lazy.
}
$(this.form).prepend(h_arr); //adds in our created hidden fields.
var form = $(this.form).children('.extra-field-wrapper');
//Gets the fieldset wrapper.
form.empty();
//Empties any children there already. Otherwise extra children are added.
for (var i = 0; i < n; i++) {
var fs_clone = fieldset.clone(); //clones the fieldset element
var l_clone = legend.clone().text("Item " + (i + 1));
// clones the legend element and adds text
var la_clone_1 = label.clone();
//label clone 1
var input_clone_1 = input.clone();
//Input clone 1
var child_wrapper_clone = child_wrapper.clone().prop('id', 'parent-' + (1 + i));
//We use clones to keep our initial values safe. This way we can alter the clones without changing our defaults
fs_clone.append(l_clone);
//Adds our legend up top for readability;
la_clone_1.prop('for', 'id-items-' + i + '-item').html('Parent ' + (i + 1));
//Adds the 'for' property with the correct ID, then sets the HTML. Item and Item2 were getting confusing
input_clone_1.prop('value', 0).prop('id', 'id-items-' + i + '-item');
//Sets the default value to 0, and the necessary ID for our label to work
var la_clone_2 = label.clone().html('# of Children').prop('for', 'id-items-' + i + '-num-children');
/*
This is a lot in one line, it clones the label element, adds the HTML, and sets the property all in one.
*/
var input_clone_2 = input.clone().prop('id', 'id-items-' + i + '-num-children').prop('value', 0).addClass('children_age');
//See above comment. One difference is that this adds our class for our next function to work
fs_clone.append([la_clone_1, input_clone_1, la_clone_2, input_clone_2, child_wrapper_clone]);
//This could probably be cleaned up, but for now it works.
form.append(fs_clone); //adds the fieldset clone to the form.
} //End for
});
$(".extra-field-wrapper").on('change', '.children_age', function(e) {
var n = $(this).val() || 0;
// the current value of the item
var append_array = [];
//Add an HTML append array, lessens calls to the $(this).next().append();
$(this).before(h_arr);
//Adds the hidden elements before this element
$(this).next('.child-wrapper').empty();
//Clears the child elements
for (var i = 0; i < n; i++) {
var l_clone = label.clone().html('Children Age' + (i + 1));
var i_clone = input.clone().addClass('child-age').prop('value', 0);
append_array.push(l_clone);
append_array.push(i_clone);
//Adds the elements to the append_array since we are now done with them.
}
$(this).next('.child-wrapper').append(append_array);
//Adds all created elements;
var children_age = $('input.child-age').each(function(i, el) {
var self = $(el);
//Lazy handle
var label = $(el).prev();
//The label is the element in front of our current element.
label.text("Child Age " + (i + 1)).prop('for', 'id_childrenage_' + i + '_childrenage');
//Gives correct label number /re does the for property;
self.prop('id', 'id_childrenage_' + i + '_childrenage');
//give correct id now that changes have been made to the dom.
});
var hidden_fields = [{
name: 'TOTAL_FORMS',
value: children_age.length
}, {
name: 'INITIAL_FORMS',
value: 0
}, {
name: 'MIN_NUM_FORMS',
value: 0
}, {
name: 'MAX_NUM_FORMS',
value: 15
}];
//We have to redeclare this function here in order for the value: n to work correctly.
if ($('#id_childrenage-TOTAL_FORMS').length == 0) {
//This element does not exist yet in the DOM
var hidden_fields = [{
name: 'TOTAL_FORMS',
value: children_age.length
}, {
name: 'INITIAL_FORMS',
value: 0
}, {
name: 'MIN_NUM_FORMS',
value: 0
}, {
name: 'MAX_NUM_FORMS',
value: 15
}];
//We have to redeclare this function here in order for the value: n to work correctly.
var h_arr = create_hidden_fields('childrenage', hidden_fields);
//creates the hidden fields
$(this.form).prepend(h_arr);
} else {
$('#id_childrenage-TOTAL_FORMS').val(children_age.length);
}
});
});
label {
font-weight: 800;
}
input[type="number"] {
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="">
<label for="id_count-count">Count:</label>
<input id="id_count-count" type="number" name="count-count">
<div class="extra-field-wrapper"></div>
<input type="submit" value="Submit">
</form>
The Explanation
I did a few things here, and there is more than likely a better way, but I did the best with my own time constraints.
I create the items to copy into the with jQuery because I'm old school and I just do not remember anything about how the template tag works so I stay away from it's particular variety of magics. The fieldset and legend are there solely for readability. In your actual code you can just delete their references as well as fs_clone and l_clone, instead attach the items directly to the form element.
I created a function that exists solely within the realm of our wrapping anonymous function called create_hidden_fields, as a programmer, mathematician, and all around lazy person I noticed the pattern in the naming convention and this appealed to me more than having to create and copy a bunch of items by hand every time I wanted to create a field.
I have the id_childrenage-TOTAL_FORMS (which is, by the way, the weirdest naming convention I've ever come across) to the form itself. Since we don't need more than 1 copy of the input.
The reason the hidden_fields array is redeclared in both functions is fairly simple: if it is declared before the variable n is, the TOTAL_FORMS input won't have the correct value. Not good.
Hopefully everything else can be answered by my comments in the code itself.
Happy Coding.

Name and ID changing

I try to build an register form. This register form as text box called "address1" and near it a button called "Add Address". The function of the button - it adds text box for more addresses. the button near the previous address boxes changes to "Remove" which remove the address box and the button. The problem is: I have to set the text boxes in order - 1,2,3,... - I have to change their names and id's. For example - if I remove addressbox number 4 (name, id="address4") then all the next text boxes's names and id's should decrease by 1. I try to do this in for loop. This is hard to explain so I just give you the code. Try in your VS to write for example 'document.getElementById("address"+n).' and you'll see that you even don't see in the list you get that you can write after the dot id or name or value. I realized it is because there is a variable in this is the problem I think. Now here's the code:
<html>
<head>
<title>Untitled Page</title>
<script type="text/javascript">
var n1 = 1; //counting the buttons and divs. doesn't decrease.
//In another words - it counts the number of calls to Add()
var n3 = 1; //counting the address text fields.
//It being reduced and increased so that it will represent the exact number of text fields
function Add() {
n1++;
n3++;
s1 = "<div id='div" + n1 + "'>";
s1 += "Address <input type='text' name='address" + n3 + "' id='address" + n3 + "' />";
s1 += "<input type='button' name='add" + n1 + "' id='add" + n1 + "' value='Add Branch' onclick='Add();' /><br />";
s1 += "</div>";
var n2 = n1 - 1;
document.getElementById('div' + n2).insertAdjacentHTML('afterEnd', s1);
document.getElementById('add' + n2).onclick = function () { Remove(n2, (n3-1)); };
document.getElementById('add' + n2).value = 'Remove';
}
function Remove(nn1, nn2) { //nn1 - div number to remove. nn2 - the address field number in this div
var parent = document.getElementById('barcode');
var child = document.getElementById('div' + nn1);
parent.removeChild(child);
for (nn2 += 1; nn2 <= n3; nn2++) {
var n2 = nn2 - 1; //nn2 - current address text field. n2 - the new number for the address field
document.getElementById('address' + nn2).setAttribute('name', 'address' + n2);
document.getElementById('address' + nn2).setAttribute('id', 'address' + n2);
document.getElementById('address' + n2).setAttribute('value', 'address' + n2);
// try: document.getElementById('address' + nn2).name='address'+n2. doesn't work (for me)
}
n3--;
}
var check = false;
</script>
</head>
<body>
<form name='barcode' id='barcode' action="" >
<div id='div1'>
Address <input type='text' name='address1' id='address1' />
<input type='button' name='add1' id='add1' value='Add Branch' onclick='Add();' /><br />
</div></form>
</body>
</html>
Sorry for the disorder :) I keeped in this code only what linked to the address field and I added comments.
Thanks very much!
edit:
I forgot that you don't see the bug in this code because I already tried to fix it. Before I changed the code it ordered all the divs, text fields and add/remove buttons so all the exsisting items will always be numbered in order (1, 2, 3, ...).
The problem in the following code can be seen if you click 2 times add button, then you remove the first address field and then you click the add button again.
<html>
<head>
<script type="text/javascript">
var n1 = 1;
function Add() {
n1++;
s1 = "<div id='div" + n1 + "'>";
s1 += "Address <input type='text' name='address" + n1 + "' id='address" + n1 + "' />";
s1 += "<input type='button' name='add" + n1 + "' id='add" + n1 + "' value='Add Branch' onclick='Add()' /><br />";
s1 += "</div>";
var n2 = n1 - 1;
document.getElementById('div' + (n2)).insertAdjacentHTML('afterEnd', s1);
document.getElementById('add' + (n2)).onclick = function () { Remove(n2); };
document.getElementById('add' + (n2)).value = 'Remove';
}
function Remove(n) {
var parent = document.getElementById('barcode');
var child = document.getElementById('div' + n);
parent.removeChild(child);
for (n += 1; n <= n1; n++) {
var n2 = n1 - 1;
document.getElementById('add' + n).onclick = function () { Remove(n2); };
document.getElementById('address' + n).setAttribute('name', 'address' + n2);
document.getElementById('add' + n).setAttribute('name', 'add' + n2);
document.getElementById('address' + n).setAttribute('id', 'address' + n2);
document.getElementById('add' + n).setAttribute('id', 'add' + n2);
document.getElementById('div' + n).setAttribute('id','div' + n2);
}
n1--;
document.getElementById('add' + n1).onclick = function () { Add() };
}
</script>
</head>
<body>
<form name='barcode' id='barcode' action="" >
<div id='div1'>
Address <input type='text' name='address1' id='address1' />
<input type='button' name='add1' id='add1' value='Add Branch' onclick='Add();' /><br />
</div>
</form>
</body>
</html>
I think you are working a bit too hard to maintain the order of the addresses and i don't see a general reason to do it (if you have one, please add it to your question).
If you add the inputs with a unique index like you are doing, they will always be different and ordered.
Here's what you can do:
Pass the event caller to the functions Add and Remove and inside you can make the changes you want to those elements.
For example your Remove function (that you would call with Remove(this);) would look like this:
function Remove(callerButton) {
var parent = document.getElementById('barcode');
var child = callerButton.parentNode;
// child is the DIV you want to remove
parent.removeChild(child);
n3--;
}
This way you wouldn't need to do all the sorting you are doing right now.
At the end you can access all the remaining elements with:
var addresses = document.getElementById("barcode").getElementsByTagName("input");
for(var i = 0; i < addresses.length; i++) {
if(addresses[i].type == "text") {
// I'm printing them in the console, you can do with it whatever you like
// If you want to exclude the one with "Add Branch in front of it you can validate for address+n1
console.log("Element.id : " + addresses[i].id + " - Element.value: "+ addresses[i].value );
}
}
I added a jsFiddle with these changes (added a submit button to show the remaining fields in the form).
See if it solves your problem.

Categories