Set ID for input elements when creating them dynamically - javascript

How can I set an input field ID when creating them dynamically when the user clicks a button.
I have a text field and a combo box pair which will be created on click. So every time the user clicks and creates one pair, I need to assign them unique IDs so that these value pairs can be saved to an array for later retrieval.
function createattr() {
var input = document.createElement("input");
input.type = "text";
input.placeholder="Attribute name";
input.className = "attr-textfield-style";
inputval.appendChild(input);
//Display the drop down menu
var newDiv=document.createElement('div');
var html = '<select>', attrtypes = typeGenerate(), i;
for(i = 0; i < attrtypes.length; i++) {
html += "<option value='"+attrtypes[i]+"'>"+attrtypes[i]+"</option>";
}
html += '</select>';
newDiv.className="attr-combobox-style";
newDiv.innerHTML= html;
inputval.appendChild(newDiv);
}

Solved it. It was this one simple line.Just wanted to share this for future references.
input.id="attr"+attrID;
with attrID being declared as a global variable that is incremented before the function ends so that each input field is assigned a unique ID
I just added the 'attr' string to an ID so that the combobox selected along with this text field will have the same numeral (i.e. One pair-> text field id- attr3, combobox- type3. The next pair will have -> text field id- attr4, combobox- type4)

if the elements never get deleted, you could count existing elements and give ID accordingly, like:
var newId = document.getElementsByClassName('attr-combobox-style').length;
input.id = 'attr' + newId;
Or you could use timestamp, it will be absolutely unique:
input.id = 'attr' + new Date().getTime();

Related

how to obtain the drop down selected option from a dynamic table

I am trying to extract selected option from a dynamically created table column. The code below works to extract the input values but not for the drop down values.
Dynamically generate HTML
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><input name='Letter"+i+"' type='text' placeholder='Letter' class='form-control input-md' /> </td><td><input name='Start"+i+"' type='text' placeholder='Start' class='form-control input-md'></td><td><input name='End"+i+"' type='text' placeholder='End' class='form-control input-md'></td> <td> <select name='cars' id='cars'><option value='All'>All</option><option value='Even'>Even</option><option value='Odd'>Odd</option></select></td>");
javascript code
// start from the second row as the first one only contains the table's headers
for (let i = 1; i < targetTableRows.length; i++) {
var Inventorydict ={}
// loop over the contents of each row
for (let j = 0; j < targetTableRows[i].cells.length; j++) {
// something we could use to identify a given item
let currColumn = tableHeaders.cells[j].innerHTML;
// the current <td> element
let currData = targetTableRows[i].cells[j];
// the input field in the row
let currDataInput = currData.querySelector('input');
// is the current <td> element containing an input field? print its value.
// Otherwise, print whatever is insside
currDataInput ? console.log(`${currColumn}: ${currDataInput.value}`)
: console.log(`${currColumn}: ${currData.document.getElementById("addressType")}`);
if (currDataInput) {
Inventorydict[currColumn.replace(/\s/g, '')] = currDataInput.value;
} else {
Inventorydict[currColumn.replace(/\s/g, '')] = currData.innerHTML;
}
}
I use this to get the input values
let currDataInput = currData.querySelector('input');
I tried using this to get the selected option
let addresstype = currColumn.getElementById("addressType")
but it does not work. How can I obtain the drop down selected option ?
currColumn is being given a value in this point of your code:
let currColumn = tableHeaders.cells[j].innerHTML;
The innerHTML property returns a string, that's why you cannot use querySelector on it.
First of all, if you want to get the value of the select once every row, you should move that section outside of that inner cycle, that loops through each cell of that row.
Then, you will need to get a reference of the tr html element. This should be targetTableRows[i].
You can get your select element by using the querySelector on this element:
for (let i = 1; i < targetTableRows.length; i++) {
var Inventorydict ={}
// ...
let select = targetTableRows[i].querySelector("select");
let selectValue = select.value; // This will map to the "value" property of the selected option
}
However, please keep in mind that you should really select elements based on their class or input name, not by their type. Also, you should not assign the same id to multiple element of your page. This will help you avoid errors that will be hard to troubleshoot.

Get ids of checked check boxes in a form using pure javascript

I have a table- each row has a checkbox of name checkBoxDelete. The id of the check box is unique(used the customer id).
I would like to get all the unique ids that were selected. So, I started by gathering all the elements of the form. Then check if it is a checkbox that is checked. If it is ,then get it's id.
var elLength = document.deleteForm.elements.length;
for (var i=0; i<elLength; i++){
var type = deleteForm.elements[i].type;
if (type=="checkbox" && deleteForm.elements[i].checked){
var rowID=deleteForm.elements[i].id;
checkedIds += rowID + ";" ;
count++;
}
}
However, rowID is always ";".
I believe I am not getting a reference to the checkbox correctly.
Change this var rowID=deleteForm.elements[i].id; to var rowID= document.deleteForm.elements[i].id;
You forgot document before selecting deleteForm

How to set values in dynamically created text boxes

In my app I am creating some dynamic textboxes by clicking an add button. We can put some values and time also. Now my need is that when the page loads, I want a given number of textboxes to be created and populated by a set of values. I am able to create the text boxes onload but cannot set the values. Here I am giving a fiddle where I have created my functionality. How can I set some values dynamically? Here is the fiddle MYFIDDLE
And also I want timepicker function in those onload created boxes.
function getTextBoxAfterValiddation(val){
var str_array = ['jeet','chatterjee'];
var randomId = '\''+"#interviewName"+val+'\'';
var nameId = "interviewName"+val+"";
var allNames = str_array.replace(/((\[)|(\]))/g,"");
alert(randomId)
$(randomId).val(arr[val]);
return '<input class="txt1" name = "DynamicTextBox" type="text" id = "'+nameId+'"/>';
}
for(var i = 0; i < 4; i++){
var div = $("<div />");
div.html(getTextBoxAfterValiddation(i));
$("#TextBoxContainer").append(div);
}
When you dynamically generate each element increment a counter and use that value as the elements id. Then you can put html or values into each element using jquery. In the example below every time i click a button with id "addphys" i append a new div on. Later i can grab values from each div because i know the count and each new div id is phys1, phys2, phys3...
var numphys = 0;
$("#addphys").click(function(){
$("#test").append("<div class=\"addedphys\"><p id=\"phys"+ numphys + "\"><p><label>Physician Username:</label><input type=\"text\" class=\"inputbox\" id=\"physusername" + numphys + "\" name=\"pass\"></p><p><label>Physician Password:</label><input type=\"text\" class=\"inputbox\" id=\"physpassword" + numphys + "\" name=\"pass\"></p></p></div>");
numphys += 1;
});
Hope that helps.

Adding a working select element to an existing table

I have a JavaScript function that adds a new row to a table. It works absolutely fine adding data types such as input (text), textbox, and radio. It also works using
document.createElement('select');
but as soon as I try to add elements, the button that triggers the JS function does nothing, which I assume means there's an error but I don't get any indication of what the problem is. I'm sure I've just missed something simple but it's been holding me back for hours and it's driving me insane!
The main body of the function is fine, because any other data type creates and adds itself to the table cell accordingly. An example of JS that works correctly within the function:
// inner left cell - text input
var cellTwo = row.insertCell(1);
var el = document.createElement('input');
el.type = 'text';
el.name = 'col' + rowNumber;
el.id = 'col' + rowNumber;
cellTwo.appendChild(el);
The code to try and create a select element with working options: (N.B. this works if I comment out the options part and simply create an empty select element, so the error MUST be somewhere within the foor loop and must just be a result of my misunderstanding how to create options dynamically:
// inner right cell - select box
var cellThree = row.insertCell(2);
//create select element
var dropDown = document.createElement('select');
//give select element id and name
dropDown.id = 'fieldtypecol' + rowNumber;
dropDown.name = 'fieldtypecol' + rowNumber;
//declare array values to put in option elements
var optionValue[] = new Array('varchar(255)', 'int', 'date', 'float(53)');
var optionText[] = new Array('String', 'Integer', 'Date', 'Float');
//declare option element holder
var option;
//loop through creating and adding values to options
for (var i = 0; i < 4; i++)
{
option = document.createElement('option');
option.value = optionValue[i];
option.text = optionText[i];
//append current option before loop restarts
dropDown.appendChild(option);
}
//append select element to new table cell
cellThree.appendChild(dropDown);
Any help would be much appreciated, thanks.
It appears in your codes the lines;
var optionValue[] = new Array('varchar(255)', 'int', 'date', 'float(53)');
var optionText[] = new Array('String', 'Integer', 'Date', 'Float');
Should be;
var optionValue = new Array('varchar(255)', 'int', 'date', 'float(53)');
var optionText = new Array('String', 'Integer', 'Date', 'Float');
Types are dynamic in JS, I would have thought these errors would appear in the JS console for you.

Get value of dynamically created textbox using JavaScript

I'm using JavaScript to dynamically add rows to a table, I create some textboxes in each row, I've added an onkeyup event to one of my textboxes:
var myTotal = "1";
var spanTotal = document.createElement("span");
spanTotal.innerHTML = "<input style=\"width:50px\" type=\"text\" name=\"total\" value=" + myTotal + ">";
spanCount.onkeyup = function ()
{
alert(spanTotal.innerHTML);
};
then I add this span (which is rendered as an HTML textbox) to my table row. I want to have value of my dynamically created textbox, but whenever I change this textbox, initial value of this textbox is displayed in alert box (i.e. 1). Initial value of this textbox is "1", but when I change it (for instance type a 0 in textbox), again "1" is displyaed in alert box. I want to have value of my dynamically created textbox, should I give an ID to my span? how should I define spanCount.onkeyup function? where should it be defined so that I can have exact value of this textbox?
I created a jsFiddle. You can get value of input box using childNodes. There are other problems in code you were using spanCount istead of spanTotal.
Modified code:
var myTotal = "1";
var spanTotal = document.createElement("span");
spanTotal.innerHTML = "<input style=\"width:50px\" type=\"text\" name=\"total\" value=" + myTotal + ">";
document.body.appendChild(spanTotal);
spanTotal.onkeyup = function() {
alert(spanTotal.childNodes[0].value);
};​
Below modified code maybe can solve your problem:
var myTotal = 1;
/* object creation */
var span = document.createElement('span');
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('name', 'total');
input.setAttribute('style', 'width:50px;');
input.setAttribute('value', myTotal);
// append each object to respective container
span.appendChild(input);
document.appendChild(span);
/* event handler */
input.onkeyup = function(){
alert(this.value);
}

Categories

Resources