create `select` element using javascript - javascript

I have an html table that I am creating dynamically its populating everything Accept select element I tried all the methods but its not working please have a look.
My complete code for table:-
function getreferData(dataArray) {
let selectArray = ["Intvw Scheduled", "Selected", "Rejected", "On Hold"];
var ray = dataArray.splice(0, 1)
let table = document.getElementById('thead1');
var tableHeaderRow = document.createElement("tr");
table.appendChild(tableHeaderRow);
for (i = 0; i < ray[0].length; i++) {
var tableHeader = document.createElement("th");
tableHeaderRow.appendChild(tableHeader);
tableHeader.innerHTML = ray[0][i];
}
let tbody = document.getElementById('perf');
for (var i = 0; i < dataArray.length; i++) {
let row = document.createElement("tr")
for (var j = 0; j < dataArray[i].length; j++) {
if (j == 4) {
let col = document.createElement("td")
var a = document.createElement("a");
a.setAttribute("class", "light-blue-text text-light-blue")
a.href = dataArray[i][j];
var node = document.createTextNode("Click here")
a.appendChild(node)
col.appendChild(a)
row.appendChild(col)
} else if (j == 6) {
var col = document.createElement("td");
col.appendChild(createDropdown("status-" + dataArray[i]));
var lbl = document.createElement("label");
lbl.setAttribute("for", "status-" + dataArray[i]);
col.appendChild(lbl)
row.appendChild(col)
} else if (j == 7) {
let col = document.createElement("td")
var a2 = document.createElement("a");
a2.setAttribute("class", "btn blue-grey darken-3 waves-effect waves-light");
a2.setAttribute("onclick", "editrefrecord(\"" + dataArray[i] + "\")");
a2.setAttribute("style", "color: white");
var node2 = document.createTextNode("UPDATE");
a2.appendChild(node2);
col.appendChild(a2);
row.appendChild(col)
} else {
let col = document.createElement("td")
col.innerText = dataArray[i][j]
row.appendChild(col)
}
}
tbody.appendChild(row);
}
function createDropdown(id) {
//create a radio button
var fragment = document.createDocumentFragment();
var select = document.createElement('select');
select.setAttribute("id", id);
selectArray.forEach(function (r) {
select.options.add(new Option(r, r));
});
fragment.appendChild(select);
return fragment;
}
}
The only thing you would like to focus is:-
let selectArray = ["Intvw Scheduled", "Selected", "Rejected", "On Hold"];
else if (j == 6) {
var col = document.createElement("td");
col.appendChild(createDropdown("status-" + dataArray[i]));
var lbl = document.createElement("label");
lbl.setAttribute("for", "status-" + dataArray[i]);
col.appendChild(lbl)
row.appendChild(col)
}
and the function to create select element :-
function createDropdown(id) {
//create a radio button
var fragment = document.createDocumentFragment();
var select = document.createElement('select');
select.setAttribute("id", id);
selectArray.forEach(function (r) {
select.options.add(new Option(r, r));
});
fragment.appendChild(select);
return fragment;
}
Currently My Html table looks like this and If you will see Status is not populating select option:-
The Inspect Element shows its created but its invisible:-

You Missed adding options
let selectArray = ["Intvw Scheduled", "Selected", "Rejected", "On Hold"];
var selectList = document.createElement("select");
selectList.id = "mySelect";
myParent.appendChild(selectList);
//Create and append the options
for (var i = 0; i < selectArray.length; i++) {
var option = document.createElement("option");
option.value = selectArray[i];
option.text = selectArray[i];
selectList.appendChild(option);
}

Related

To create a custom table by getting values from a dynamicaly created table

what I want is on save click to show another table like below where the second column(Questions) has sub-columns depending maximum L value a row has:
unit Question
unit1 23(L1)
unit2 23(L3)
unit3 24(L3)
unit4 6(L2)
unit4 10(L4)
unit5 7(L1)
unit5 10(L6)
unit6 10(L2)
unit 7(L4)
var x = [];
function getval() {
var trs = $('#DyanmicTable3 tr:not(:first-child):not(:nth-last-child(2)):not(:last-child)');
var trs1 = $('#DyanmicTable3 tr:last-child');
var lastTotalElement = $('#DyanmicTable3 tr:nth-last-child(2)');
console.log(trs1);
for (let i = 2; i <= 7; i++) {
const total = Array.from(trs)
.reduce((acc, tr) => x.push(Number(tr.children[i].textContent)), 0);
;
}
console.log(JSON.stringify(x));
}
this is wt i got so far getting values in an array
function GenerateTable() {
var grid = new Array();
grid.push(["Unit", "Marks", "Bloom Level"]);
var tb = $('#DyanmicTable3:eq(0) tbody ');
tb.find("tr:not(:first-child):not(:nth-last-child(2)):not(:last-child)").each(function (index, element) {
var colValtst;
$(element).find('th:not(:first-child):not(:nth-last-child(2)):not(:last-child)').each(function (index, element) {
colValtst = $(element).text();
});
$(element).find('td').each(function (index, element) {
var colVal = $(element).text();
let y = $(element).index();
if (colVal != '') {
console.log(" Value in " + colValtst + " : " + colVal.trim() + " L" + y);
//add grid here
grid.push([colValtst, colVal.trim(), "L" + y]);
}
});
});
//Build an array containing Customer records.
// $('#save').attr('href', 'AddQuestions.aspx?val1=' + grid + '');
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Get the count of columns.
var columnCount = grid[0].length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = grid[0][i];
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < grid.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = grid[i][j];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);

Is option to assign ID to every checkbox inside dynamic table

This is my dynamic table
After clicking button it generate table based on input.
$(function () {
$("#btnGenerate").click(function () {
var textarea = document.getElementById("inglist");
var lines = textarea.value.replace(/\r\n/g,"\n").split(/:|,|\n/);
var lines2 = textarea.value.split(/(\d+(?:\.\d+)?)/);
lines.forEach((o, i) => o.id = i + 1);
var array1=new Array();
for (var i = 1; i < lines .length; i++) {
array1.push(lines [i].replace(/\[.*?\]/g, ''));}
const results = [];
array1.forEach(line => {
const filtered = line.split(/([\s\w]+)\s(\d+(?:\.\d+)?)(%?)\s*(\[\d\])?/g).filter(Boolean);
results.push(filtered);
});
var build = new Array();
build.push(["ING name:", "Total:","unit", "Count it?:","x2?"]);
var table1 = $("<table />");
for(var i=0;i<results.length;i++){
build.push(results[i]);
}
var countColumns = build[0].length;
console.log(countColumns);
var tables = $("<table /><class='form-control input-md'>");
//Add the header row.
var rows = $(tables[0].insertRow(-1));
for (var i = 0; i < countColumns; i++) {
var headerCell = $("<th /><class='form-control input-md'>");
headerCell.html(build[0][i]);
rows.append(headerCell);
}
//Add the data rows.
for (var i = 1; i < build.length; i++) {
row = $(tables[0].insertRow(-1));
for (var j = 0; j < countColumns; j++) {
var cell = $('<td><input type="checkbox"/>');
cell.html(build[i][j]);
row.append(cell);
}
}
var dvTable1 = $("#dvTable1");
dvTable1.html("");
dvTable1.append(tables);
});
How i can assign dynamic ID to every checkbox ?
And then how to filter only rows where is tick checkbox in 3rd column ( count in?: )

How "tblGene()" call on JavaScript page.I am want to call on HTML page using onclick.. Without click this Json table show on my web page

How tblGene() call on JavaScript page. I do not want to call on HTML page using onclick. Without click, this JSON table show on my web page. Please help me. When page was loaded this JSON table on my web page. I do not want to use input box for click.
<input type="button" onclick="tblGene()" value="Click Here to Generate Table" style="width:100% height:100%" />
<div id="showData"></div>
var people, asc1 = 1;
function tblGene() {
var data = [{"rollno":1234,'name': "jetta",'marks': 600,'percentage': 1222,'bestscore': 99},{"rollno":2341,'name': "jetta",'marks': 700,'percentage': 1222,'bestscore': 100},{"rollno":3421,'name': "jetta",'marks': 500,'percentage': 1222,'bestscore': 90},{"rollno":4321,'name': "jetta",'marks': 400,'percentage': 1222,'bestscore': 95},{"rollno":2043,'name': "jetta",'marks': 550,'percentage': 1222,'bestscore': 80},];
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
tbody.id = "people";
var tbl = document.createElement("table");
tbl.id = "tblSample";
var col = [];
for (var i = 0; i < data.length; i++) {
for (var colHdr in data[i]) {
if (col.indexOf(colHdr) === -1) {
col.push(colHdr);
}
}
}
var tr = tbl.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
th.dataset.key = i;
tr.appendChild(th);
}
thead.appendChild(tr);
for (var i = 0; i < data.length; i++) {
tr = tbl.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var td = document.createElement("td");
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[i][col[j]];
}
tbody.appendChild(tr);
}
tbl.appendChild(thead);
tbl.appendChild(tbody);
var divCntr = document.getElementById("showData");
divCntr.innerHTML = "";
divCntr.appendChild(tbl);
thead.addEventListener("click", function(event) {
var key = event.target.dataset.key;
people = document.getElementById("people");
sort_tbl(people, key, asc1);
});
function sort_tbl(tblSample, key, asc) {
var rows = tblSample.rows,
rlen = rows.length,
arr = new Array();
for (var i = 0; i < rlen; i++) {
var cells = rows[i].cells;
var clen = cells.length;
arr[i] = new Array();
for (var j = 0; j < clen; j++) {
arr[i][j] = cells[j].innerHTML;
}
}
arr.sort(function(x, y) {
if (isNaN(x[key]) && isNaN(y[key])) {
var a = String(x[key]).toUpperCase();
var b = String(y[key]).toUpperCase();
if (a > b)
return 1
if (a < b)
return -1
return 0;
} else {
return x[key] - y[key];
}
});
for (i = 0; i < rlen; i++) {
rows[i].innerHTML = "<td>" + arr[i].join("</td><td>") + "</td>";
}
}
}
Just remove the () from you onclick handler, like this onclick="tblGene".
If you leave the (), you're executing the function as soon as the <input> element is loaded - in your case on page load.

Image is not appearing inside the loop

I want an image to be added inside the table for every loop run.image is not appearing any help will be appreciated thank u
for (var i = 0; i < result.length; i++) {
doc1 = result[i];
if (doc1.PHOTO == "") {
var elem1 = document.createElement("img");
elem1.setAttribute("src", '../common/images/Icon-60.png');
elem1.setAttribute("height", "60");
elem1.setAttribute("width", "60");
var tbody = $("<tbody>").appendTo(table);
var tr = $("<tr>").appendTo(tbody);
var td = $("<td>").html(doc1.ENAME).data(doc1).appendTo(tr);
var tr2 = $("<tr>").appendTo(tbody);
var td2 = $("<td>").html(elem1).appendTo(tr2);
}
I'm not sure this will solve your problem, but try :
for (var i = 0; i < result.length; i++) {
var doc1 = result[i];
if (doc1.PHOTO == "") {
var elem1 = "<img src='../common/images/Icon-60.png' height='60' width='60'/>");
table.append('<tr><td data-name='+doc1+'>'+doc1.ENAME+'</td></tr><tr><td>'+elem1+'</td></tr>');
}
}
Hope this helps.

How to check value of table td?

I am trying to create mine field game. "I am very new to Js".
What I have done so far:
var level = prompt("Choose Level: easy, medium, hard");
if (level === "easy") {
level = 3;
} else if (level === "medium") {
level = 6;
} else if (level === "hard") {
level = 9;
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 1; i <= 10; i++) {
var row = document.createElement("tr");
document.write("<br/>");
for (var x = 1; x <= 10; x++) {
var j = Math.floor(Math.random() * 12 + 1);
if (j < level) {
j = "mined";
} else {
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + " ");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
So I create here 2d table and enter 2 random values in rows and columns (mined or clear).
Where I am stuck is:
Check if td = mined it dies otherwise open the box(td) etc.
How do I assign value of td? I mean how can I check which value(mined/clear) there is in the td which is clicked?
Ps: Please don't write the whole code:) just show me the track please:)
Thnx for the answers!
Ok! I came this far.. But if I click on row it gives sometimes clear even if I click on mined row or vice versa!
// create the table
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute('id','myTable');
var tblBody = document.createElement("tbody");
//Create 2d table with mined/clear
for(var i=1;i<=10;i++)
{
var row = document.createElement("tr");
document.write("<br/>" );
for(var x=1;x<=10;x++)
{
var j=Math.floor(Math.random()*12+1);
if(j<level)
{
j = "mined";
}
else{
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + "");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
if(id === "mined")
{
alert("You died");
}else
{
alert("clear");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
I think I do something wrong with giving the table id "myTable"..
Can you see it?
Thank you in advance!
So, the idea would be:
assign a click event to each td cell:
td.addEventListener('click', mycallback, false);
in the event handler (callback), check the content of the td:
function mycallback(e) { /*e.target is the td; check td.innerText;*/ }
Pedagogic resources:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td?redirectlocale=en-US&redirectslug=HTML%2FElement%2Ftd
https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
JavaScript, getting value of a td with id name

Categories