Adding a working select element to an existing table - javascript

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.

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.

Set ID for input elements when creating them dynamically

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();

link a checkbox to an object in Javascript

Suppose I have a table which is populated by filling out a form on a page and clicking the submit button.
The last column of the table is a Completed section with a checkbox on each row. On clicking on the checkbox I want to change the .completed property from false to true on that object.
How can I distinguish which checkbox was clicked and change the property from that row?
this.addRowToTable = function() {
return "<tr id='tableRow'><td>" + this.app + "</td><td>" + this.priority + "</td><td>" + this.date + "</td><td>" + this.additionalNotes + "</td><td>" + "<input type='checkbox' class='checkApp[]' value='" + this.completed + "' />" + "</td></tr>";
};
I have all the checkboxes in the checkApp array, but Im not sure where to go from there?.
This is called when the form is submitted:
function addAppointment() {
if (txtApp.value == "" || txtPriority.value == "" || txtDate.value == "" || {
alert("Please fill all text fields");
} else {
var app = new Appointment(txtApp.value, txtPriority.value, txtDate.value, txtNotes.value, false);
apps.push(app);
localStorage.setItem("apps", JSON.stringify(apps));
clearUI();
}
updateTable();
updateTable() loops through all objects in my array and adds them between table tags:
for (var i = 0; i < apps.length; i++) {
var app = new Appointment(apps[i].app, apps[i].priority, expenses[i].date, apps[i].notes, false);
tblHTML += app.addRowToTable();
}
My Appointment Object:
function Appointment(app, priority, date, notes, completed) {
this.app = app;
this.priority = priority;
this.date = date;
this.additionalNotes = notes;
this.completed = completed;
this.addRowToTable = function { ... };
}
First of all, in HTML, id attributes should be unique. So, make sure table rows have unique IDs. At the moment, all of them have the identical ID of tableRow.
Besides, you should consider using a framework/library such as jQuery for real-world scenarios rather than creating the DOM elements, etc. manually.
Now back to the original problem: if you use the DOM API rather than string concatenation to create the table rows, you can add custom fields to the DOM objects representing the table rows. So, from each table row, you can have a reference back to its corresponding Appointment object:
var row = document.createElement("tr");
row.appointment = this;
Similarly, you can use the DOM API to create the table cells as well as the checkbox:
addTd(row, this.app);
addTd(row, this.priority);
addTd(row, this.date);
addTd(row, this.additionalNotes);
var input = document.createElement("input");
var td = document.createElement("td");
td.appendChild(input);
row.appendChild(td);
input.setAttribute("type", "checkbox");
input.setAttribute("class","checkApp[]"); // Why checkApp[]? checkApp or check-app make more sense
input.setAttribute("value", this.completed);
where addTd is the following function:
function addTd(row, innerHTML) {
var td = document.createElement("td");
td.innerHTML = innerHTML;
row.appendChild(td);
}
Now that you are using the DOM APIs, you can easily attach event listeners to each checkbox object as well.
Then inside the event listener you can get a reference back to the Appointment corresponding to the row you
have changed its checkbox:
var row = document.createElement("tr");
row.appointment = this;
addTd(row, this.app);
addTd(row, this.priority);
addTd(row, this.date);
addTd(row, this.additionalNotes);
var input = document.createElement("input");
var td = document.createElement("td");
td.appendChild(input);
row.appendChild(td);
input.setAttribute("type", "checkbox");
input.setAttribute("class","checkApp[]"); // Why checkApp[]? checkApp or check-app make more sense
input.setAttribute("value", this.completed);
input.addEventListener("change", function(event) {
var row = this.parentNode.parentNode,
appointment = row.appointment;
// change appointment however you like
});

Getting the ID in of an ASP drop down list from client side

What I'm trying to do is get one of my drop down list to change its contents whenever the selected item in another one cahnges. I have this code in my aspx file:
function ModifyDDLItems(id1, id2)
{
var ddlcontrolShown = document.getElementById(id1);
var ddlcontrolHidden = document.getElementById(id2);
if (ddlcontrolShown.options[ddlcontrolShown.selectedIndex].value == "DD1")
{
//Get number of items of hidden ddl
var length = ddlcontrolHidden.options.length;
//Clear items of shown ddl
ddlcontrolShown.options.length = 0;
//Add itmems of hidden ddl to shown ddl
for (i = 0; i < length; i++)
{
ddlcontrolShown.options.add
var newoption = document.createElement("option")
newoption.text = ddlcontrolHidden.options[i].text;
newoption.value = ddlcontrolHidden.options[i].text.value;
}
}
}
Now, i give it the front end ID's thru this:
protected void SetDD1ConfItems(GridViewRow gvRow, DataSet BaseConfItems)
{
DataView dvConfType = new DataView(BaseConfItems.Tables[0]);
DataSet dsTemp = BaseConfItems.Clone();
DropDownList ddlConfType2 = (DropDownList)form1.FindControl("ddlConfType2");
DropDownList ddlBA = (DropDownList)gvRow.FindControl("ddlBA");
DropDownList ddlConfType = (DropDownList)gvRow.FindControl("ddlConfType");
dvConfType.RowFilter = "ref_code = 'FAX' or ref_code = 'EEX' or ref_code = 'EPD'";
dsTemp.Tables.Clear();
dsTemp.Tables.Add(dvConfType.ToTable());
ddlConfType2.DataSource = dsTemp;
ddlConfType2.DataBind();
//ddlBA.Attributes["onchange"] = "function GetDDLD(" + ddlConfType.ClientID + ", " + ddlConfType2.ClientID + ") {ModifyDDLItems(id1, id2);}";
ddlBA.Attributes.Add("onchange", "ModifyDDLItems('" + ddlConfType.ClientID + "', '" + ddlConfType2.ClientID + "')");
}
When I run it, VS keeps on telling me that id1 and id2 are both null, it seems the id's aren't passed to the client properly.
I think you have code wrongly, the first mistake i found at a glance is,
You cannot find the controls inside gridview by using
gvRow.FindControl("ddlBA");
There may be multiple rows in GridView, so you have to find your controls in each Row as all of them will have different ClientIDs. First to try to replace the below code
gvRow.Rows[RowIndex].FindControl("ControlID");
ALso, it should be written in the some kind of loop in order to find the RowIndex value of the Grid.
Describe your exact requirement in brief. So, that i can help you in writing the proper code.

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