Javascript: how get all the values and id from an inputs array? - javascript

So I'm trying to get all the values and id of every input from an array, but I have an issue, the user can duplicate the input and each input have a randomly generated ID so I can't select the data with the ID and every input use name="cate[]" so every input have the same name, so I can use something like this:
function regTour() {
var input = document.getElementsByName('cat[]');
var k = "The respective values are :";
for (var i = 0; i < input.length; i++) {
var a = input[i];
k = k + "array[" + i + "].value= "
+ a.value + " ";
}
console.log('Console: ' + k);
}
but how I can get the ID from every input from the array paired with the input value?
Edit: -------------------
the input looks like this:
<input type="text" id="1666239497429" name="cat[]" class="form-control">
<input type="text" id="12983172462" name="cat[]" class="form-control">
<input type="text" id="812361647812" name="cat[]" class="form-control">
this input it's created dynamically by the user so the id changes, this id later it's stored with other sub fields that should be related with that id, that's why it's some kind important for me be able to store all the id's

You can get the id of DOM elements using the id property. From your example, just use a.id to access it.
Side note, you should use const instead of var if the variable is not going to be changed, and let if it does change. var shouldn't be used any more.
function regTour() {
var input = document.getElementsByName('cat[]');
var k = "The respective values are :";
for (var i = 0; i < input.length; i++) {
var a = input[i];
k = k + "array[" + i + "].value= "
+ a.value + " array[" + i + "].id= " + a.id;
}
console.log('Console: ' + k);
}

can you share more data from the front? how is your form?
This ist OK var input = document.getElementsByName('cat[]'); but I'm not sure what the problem is

Related

HTML <option> tag does not display label/name value

for(let i = 0; i < this.elems.length; i++) {
document.getElementById('elemsList').innerHTML += ('<option value="'+ this.elems[i].id +' label="' +this.elems[i].name +'"></option>');
}
(it tried lable="" and name="")
produces the list for a texfield to filter through. This list displays the id value large and the label value smaller beneath it. when choosing an option the field is filled with the id value.
How do i have to change it to only display the name value both in the list and in the field, but when submitting the form it belongs to access the id value?
for(let i = 0; i < this.elems.length; i++) {
document.getElementById('elemsList').innerHTML += ('<option value="'+ this.elems[i].id +'>' +this.elems[i].name +'</option>');
}
has the same result.
I am using Angular, and the list is a <data-list>
Edit: This is what the list looks like now. I want it to just display the name. But when the form is submitted it should use the id value.
In JS i load the list like this
loadElemList() {
for(let i = 0; i < this.elems.length; i++) {
document.getElementById('elemsList').innerHTML += ('<option value='+ this.elems[i].id +'>' +this.elems[i].name +'</option>');
}
}
The HTML
<tr><td><label>Elem:</label></td><td>
<input #elem list="elemList" name="elem" />
<datalist id="elems">
</datalist></td></tr>
And the form gets the value from the list with
elem.value
Where elem.value should be the id but the user only sees the name.
I think you were missing " after the value. Try the following:
for(let i = 0; i < this.elems.length; i++) {
document.getElementById('elemsList').innerHTML += ('<option value="' + this.elems[i].id +'" label="' + this.elems[i].name + '"></option>');
}
This might produce what you want, apologies if I misunderstood the question.

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.

JavaScript & HTML - Modifying dynamically created subclasses within a dynamically created class

Problem:
I have a dynamically created HTML table, that is used for filling out time sheets. It is created programmatically - there is no formal control. The design is a mix of CSS with text boxes being created through JavaScript. Now each 'row' of this table is in a class called 'divRow', and is separated from the others by having 'r' and the number of the row assigned to it as the class (i.e 'divRow r1', 'divRow r2', etc.).
Within each of these 'divRow's, I have cells in a class called 'divCell cc'. These do not have any identifiers in the class name. At the very last cell, I have a 'Total' column, which ideally calculates the total of the row and then adds it into a dynamically created text box.
What I have at the moment:
// Function to create textboxes on each of the table cells.
$(document).on("click", ".cc", function(){
var c = this;
if(($(c).children().length) === 0) {
var cellval = "";
if ($(c).text()) {
cellval = $(this).text();
if(cellval.length === 0) {
cellval = $(this).find('.tbltxt').val();
}
}
var twidth = $(c).width() + 21;
var tid= 't' + c.id;
if(tid.indexOf('x17') >= 0){
var thtml = "<input id='t" + c.id + "' type='text' Class='tbltxt' style='width: " + twidth + "px;' readonly />";
eval(spproc(spcol(t[getx(c.id)],thtml,tid,twidth)));
//var getRow = $(this).parent().attr('class'); - this gets the 'divRow r#' that it is currently on.
var arr = document.getElementsByClassName('cc');
var tot = 0;
for(var i = 0; i<arr.length; i++){
if(parseInt(arr[i].innerHTML) > 0){
tot += parseInt(arr[i].innerHTML);}
}
$('#t' + c.id).focus();
$(this).children().val(tot);
}else{
var thtml = "<input id='t" + c.id + "' type='text' Class='tbltxt' style='width: " + twidth + "px;' />";
eval(spproc(spcol(t[getx(c.id)],thtml,tid,twidth)));
$('#t' + c.id).focus();
$('#t' + c.id).val(cellval);
}}
});
As you can see, when the user clicks on the 'divCell cc', it creates a text box if one is not present. If the user clicks on the 17th column ('x17'), then it runs the for loop, and assigns the value of the total to the text box.
What I need to happen:
So what happens now is that the last cell sums the total of each cell that has a value. However, they are not row-dependent. I need it to calculate based on the row that it is currently 'on'. So if I'm calculating the 2nd row, I don't want the sum of the first, second and third being entered into the total, I just want the 2nd rows' values summed.
What I've tried:
I've tried looping through and using the 'divRow r#' number to try and get the items in the array that end in that number. (cells are given an id of 'x#y#' and the text boxes assigned to those cells are given an id of 'tx#y#').
I've tried getting elements by the cell class name, and then getting their parent class and sorting by that; didn't get far though, keep running into simple errors.
Let me know if you need more explanation.
Cheers,
Dee.
For anyone else that ever runs into this issue. I got it. I put the elements by the row class into an array, and then using that array, I got the childNodes from the row class. The reason the variable 'i' starts at 2 and not 0 is because I have 2 fields that are not counted in the TimeSheet table (Jobcode and description). It's working great now.
Cheers.
$(document).on("click", ".cc", function(){
var c = this;
if(($(c).children().length) === 0) {
var cellval = "";
if ($(c).text()) {
cellval = $(this).text();
if(cellval.length === 0) {
cellval = $(this).find('.tbltxt').val();
}
}
var twidth = $(c).width() + 21;
var tid= 't' + c.id;
if(tid.indexOf('x17') >= 0){
var thtml = "<input id='t" + c.id + "' type='text' Class='tbltxt' style='width: " + twidth + "px;' readonly />";
eval(spproc(spcol(t[getx(c.id)],thtml,tid,twidth)));
// Get current row that has focus
var getRow = $(this).parent().attr('class');
// Get the row number for passing through to the next statement
var rowPos = getRow.split('r', 5)[1];
// Get all the elements of the row class and assign them to the rowClass array
var rowClass = document.getElementsByClassName('r' + rowPos)
// Given the rowClass, get the children of the row class and assign them to the new array.
var arr = rowClass.item(0).childNodes
// Initialize the 'total' variable, and give it a value of 0
var tot = 0;
// Begin for loop, give 'i' the value of 2 so it starts from the 3rd index (avoid the Req Code and Description part of the table).
for(var i = 2; i<arr.length; i++){
if(parseInt(arr[i].innerHTML) > 0){
tot += parseInt(arr[i].innerHTML);}
}
// Assign focus to the 'Total' cell
$('#t' + c.id).focus();
// Assign the 'total' variable to the textbox that is dynamically created on the click.
$(this).children().val(tot);
}else{
var thtml = "<input id='t" + c.id + "' type='text' Class='tbltxt' style='width: " + twidth + "px;' />";
eval(spproc(spcol(t[getx(c.id)],thtml,tid,twidth)));
$('#t' + c.id).focus();
$('#t' + c.id).val(cellval);
}}
});

How to insert a string into an array of text inputs?

Basically, I have a large string that i am splitting, then splitting again.
I then need to use the smallest split array to place its elements into text inputs on my page.
This is my Javascript
var splitquestions = vals[2].split('\n');
//Loop to go through all current questions
for (var i = 0; i < splitquestions.length - 1; i++)
{
//trigger a question add where a single question data can be added into
$( "#add" ).trigger('click');
//split current question into separate items
var s = splitquestions[i].split(',');
//Loop to go over all sections in a question
var count = 0;
for(var j = 0; j < s.length; j++)
{
count = count + 1;
var qs = document.getElementById('questions[' + j +'][' + count + ']').value;
qs = s[j];
}
}
There will be many questions on the page, depending how many the user will like to add. Each new question block will consist of a question, 3 wrong answers, and 1 correct answer.
The part that is going wrong is within the last loop. This is where I need to grab each individual element within the 's' array, and place it within each text input.
This is how the raw data is displayed before it is split by the 'splitquestions' variable:
question1,incorrect-answer1,incorrect-answer2,incorrect-answer3,correct-answer
question2,incorrect-answer1,incorrect-answer2,incorrect-answer3,correct-answer
question3,incorrect-answer1,incorrect-answer2,incorrect-answer3,correct-answer
As you can see from above, each question is separated by a line-break, being \n, then each individual part is comma separated.
Each question input has a multidimensional variable assigned to its ID. For example, using the data above, the first line of data, along with the very first element (being question1) would be question[1][1]. Another example would be 'incorrect-answer1' on the third line of data, which would be question[3][2]. The first number is the question number, and the second number is the element number.
I hope that I've explained this well enough, since I am a little confused on how to explain it myself since I am new to multidimensional arrays and loops inside loops. So please, if you need any additional information, just post a comment and I'll do my best.
If needed, this is the function that creates the question elements dynamically:
function dynamicForm () {
//set a counter
var i = $('.dynamic-input#form-step2').length + 1;
//alert(i);
//add input
$('a#add').click(function () {
$('<table><tr><td><p><span class="left"><input type="text" class="dynamic-input" name="questions[' +i +'][1]" id="' + i + '" placeholder="Question" /></span>' + '<span class="right"><input type="text" class="dynamic-input" name="questions[' +i +'][2]" id="' + i + '" placeholder="Distraction 1" /><br /><input type="text" class="dynamic-input" name="questions[' +i +'][3]" id="' + i + '" placeholder="Distraction 2" /><br /><input type="text" class="dynamic-input" name="questions[' +i +'][4]" id="' + i + '" placeholder="Distraction 3" /><br /><input type="text" class="dynamic-input" name="questions[' +i +'][5]" id="' + i + '" placeholder="Correct Answer" /><br />Remove</span></p></td></tr></table>').fadeIn("slow").appendTo('#extender');
i++;
$("a:contains('Remove')").click(function () {
$(this).parent().parent().remove();
});
return false;
});
//fadeout selected item and remove
$("#form-step2.dynamic-input").on('click', 'a', function () {
$(this).parent().fadeOut(300, function () {
$(this).empty();
return false;
});
});
}
After further discussions with the OP, we fixed the code ended up being what's below. Basically, his input numbers are starting at index 1 instead of 0, so that was one of the issues. He was also trying to select by id while the inputs in question only had a name attribute.
//Loop to go over all sections in a question
for (var j = 1, len = s.length; j <= len; j++) {
$('input[name="questions[' + (i + 1) + '][' + j + ']"]').val(s[j - 1]);
}

Change name values with JavaScript

Been at this for a long time, and it seems so simple but I cannot get it to do what I want.
Each book has a 'getOrRequest' value that is selected using radio buttons. Every time a div is duplicated, the name value needs to be changed so that a book has its own getOrRequest value. I've finally got the duplicating down, but now renaming the correct inputs isn't cooperating.
What's really bugging me is that it works, but it's not changing the name values that I'm trying to grab. It has something to do with what parts of the array are being changed, but I can't get the values that I want, namely the last two getOrRequest names.
A working example of what I'm struggling with here.
My JS function:
function addAnotherPost(){
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
copyDiv.id = 'addListing' + idNumber;
bookInfo.appendChild(copyDiv);
var divID = 'addListing' + idNumber;
var newDiv = document.getElementById(divID);
var postType = document.getElementsByName("getOrRequest[]");
alert(postType[0].name + postType[1].name + postType[2].name + postType[3].name);
for(var i = 2; i < postType.length; i++){
postType[i].name = 'getOrRequest' + idNumber + '[]';
}
alert("got this far" + postType.length);
idNumber++;
}
The relevant chunk of HTML:
<div id='addListing'>
<table class='aListing'>
<tr>
<td>
<label>
<input type='radio' name='getOrRequest[]' value='1' />
Request</label>
<label>
<input type='radio' name='getOrRequest[]' value='0' />
Offer</label>
</td>
[...]
</table>
</div>
You are getting an object list for a specific name identifier:
var postType = document.getElementsByName("getOrRequest[]");
so postType is changing once you've renamed an element (Yes man that thing is inteligent)
console.log(postType.length); // = 4
postType[i].name = 'getOrRequest' + idNumber + '[]';
console.log(postType.length); // = 3
so basically the for loops changes because postType.length changes.
I guess what you want to do is something like:
postType[0].name = 'getOrRequest' + idNumber + '[]'; //ref changed.
postType[0].name = 'getOrRequest' + idNumber + '[]';
however thats bad style anyways you should clone from a marked source and rename by name before you append to something, like so ( http://jsfiddle.net/bHLZA/2/ ):
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
copyDiv.id = 'addListing' + idNumber;
postType = copyDiv.getElementsByTagName('input');
postType[0].name = 'getOrRequest' + idNumber + '[]';
postType[1].name = 'getOrRequest' + idNumber + '[]';
bookInfo.appendChild(copyDiv);
see http://jsfiddle.net/bHLZA/

Categories