I am trying to create a table dynamically using javascript. I want each table to have a checkbox beside it. So, I have written the following code:
JAVASCRIPT
label_submit_btn.addEventListener("click", function(event){
event.preventDefault();
var formInputs = document.getElementById("label_query_form").querySelectorAll("input");
validation = validateForm(formInputs);
if(validation[0]){
var label_query_form_action = document.getElementById("label_query_form").getAttribute("action");
var label_val = document.getElementById("label_no")
query_db("label_data_div", label_query_form_action, label_val, true, "label_query_row");
// var chk_boxes = document.getElementsByClassName("form-check-input");
// document.getElementById("data_delete_btn").disabled = false;
}
else{
alert(validation[1])
}
});
function query_db(output_div, form_action, form_data, add_checkbox, row_class){
document.getElementById(output_div).innerHTML = ""
var xhr = new XMLHttpRequest();
var formData = new FormData();
formData.append(form_data.name, form_data.value)
xhr.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
let response_data = JSON.parse(this.responseText);
let table_data = JSON.parse(response_data);
table_data = create_table_from_json(table_data, add_checkbox, row_class);
document.getElementById(output_div).innerHTML += table_data;
}
}
xhr.open("POST", form_action, true);
xhr.send(formData);
}
function create_table_from_json(table_data, add_checkbox, row_class){
var table_rows = "";
for (var i = 0; i < table_data["columns"].length; i++) {
table_rows += "<th>" + table_data["columns"][i] + "</th>";
}
table_rows += "<th>Select</th>";
console.log(table_rows);
table_rows = "<tr>" + table_rows +"</tr>";
for (var i = 0; i < table_data["data"].length; i++) {
trow = ""
for (var j = 0; j < table_data["columns"].length; j++) {
trow += "<td class="+ table_data["columns"][j] +">" + table_data["data"][i][j] + "</td>";
}
if(add_checkbox == true){
trow += '<td><input type="checkbox" class="form-check-input"/> </td>';
}
table_rows += "<tr class="+ row_class + ">" + trow +"</tr>";
}
return "<table><tbody>" + table_rows + "</table></tbody>";
}
HTML
<div class="container" id="label_data_div" style="height: 200px;overflow: scroll;"></div>
Now, while rendering the page, all of the checkboxes are overflowing outside of the div element(see image).
Related
How to use table instead of list for alignment. Also ones we click the cancel button the file list need to be deleted from list.
updateList = function () {
var input = document.getElementById('fileUploader');
var output = document.getElementById('divFiles');
output.innerHTML = '<ul style="list-style-type:none">';
for (var i = 0; i < input.files.length; ++i) {
output.innerHTML += '<li>' + input.files.item(i).name + ' <button>X</button></li> ';
}
output image for the above code
updateList = function () {
var input = document.getElementById('fileUploader');
var output = document.getElementById('divFiles');var HTML = "<table>";
for (var i = 0; i < input.files.length; ++i)
{
HTML += "<tr><td>" + input.files.item(i).name + "</td><td> <button>X</button></td></tr>";
}
HTML += "</table>";
output.innerHTML = HTML;
}
The following code works only if the table is already present in the document upon page load. I however want it to apply on a dynamically created table.
Can this be done?
var colNumber=22
for (var i=0; i<colNumber; i++)
{
var thWidth=$("#tbl").find("th:eq("+i+")").width();
var tdWidth=$("#tbl").find("td:eq("+i+")").width();
if (thWidth<tdWidth)
$("#tbl").find("th:eq("+i+")").width(tdWidth);
else
$("#tbl").find("td:eq("+i+")").width(thWidth);
}
The table is created in the following way:
function loadFile(event){
alasql('SELECT * FROM FILE(?,{headers:false})',[event],function(data){
var keys = [];
for (var i = 0; i < data.length; i++) {
for (var categoryid in data[i]) {
var category = data[i][categoryid];
keys.push(categoryid);
}
}
keysConverted = keys.map(foo);
var vMin = Math.min.apply(null, keysConverted);
var vMax = Math.max.apply(null, keysConverted);
var start = vMin-1
var ColNeeded = vMax - vMin+1;
var arrExcel2Table = '<table id="tbl">';
for (var i = 0; i < data.length; i++){
arrExcel2Table = arrExcel2Table + '<tr>';
for (var j = 0; j < ColNeeded; j++){
cellValue = data[i][number2Letter(j+start)];
if (typeof cellValue === "undefined"){
cellValue = '';
}
arrExcel2Table = arrExcel2Table + '<td>' + cellValue + '</td>';
}
arrExcel2Table = arrExcel2Table + '</tr>';
}
arrExcel2Table = arrExcel2Table + '</table>';
document.getElementById('excel_table').innerHTML = arrExcel2Table;
});
}
Create a function you want to run and add an event from the dynamic element. For example
arrExcel2Table = arrExcel2Table + '<td>' + cellValue + '</td>';
can be replaced by
arrExcel2Table = arrExcel2Table + '<td onclick="myFunction();">' + cellValue + '</td>';
Above code will call the function you created
myFunction() {
alert();
}
Just create your table, then apply whatever code you want to it :
$('#excel_table').html(arrExcel2Table);
adjustWidth()
function adjustWidth(){
var $tbl = $("#tbl"); // And cache your jQuery objects!! Massive performance boost
for (var i=0; i<colNumber; i++)
{
var $th = $tbl.find("th:eq("+i+")"),
$td = $tbl.find("td:eq("+i+")"),
thWidth = $th.width(),
tdWidth = $td.width();
if (thWidth<tdWidth)
$th.width(tdWidth);
else
$td.width(thWidth);
}
}
I'm having trouble when i run this code under greasemonkey the last position working and run function.
var arry = [];
arry = GM_listValues();
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML = document.getElementById('moje_menu').innerHTML + '<p id="' + arry[i] + '">' + arry[i] + '</p>';
document.getElementById(arry[i]).onclick = delete;
}
On 10 position the last working ... WHY ????
When you replace the innerHTML you remove all previous event handlers.
In plain JS you can detect the click in the div but you need to check the event:
function removeP(p) {
console.log(p.id);
}
var arry = ["a","b","c"];
window.onload=function() {
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '">' + arry[i] + '</p>';
}
document.getElementById('moje_menu').onclick=function(e) {
var event = e?e:window.event,tgt = event.target || event.srcElement;
if (tgt.tagName.toLowerCase()=="p") {
console.log(tgt.id);
}
}
}
<div id="moje_menu"></div>
Alternative is inline since you generate the P anyway
var arry = [];
arry = GM_listValues();
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '" onclick="delete(this)">' + arry[i] + '</p>';
}
You can the modify delete (poor name for a function since delete is a built-in method) to handle the passed paragraph
Example:
function removeP(p) {
console.log(p.id);
}
var arry = ["a","b","c"];
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '" onclick="removeP(this)">' + arry[i] + '</p>';
}
<div id="moje_menu"></div>
In jQuery you can easily delegate:
function removeP() {
console.log(this.id);
}
$(function() {
var arry = ["a","b","c"];
var $menu = $('#moje_menu');
for (var i=0; i<arry.length; i++) {
$menu.append($('<p/>',{"id":arry[i], "text":arry[i]}))
}
$menu.on("click","p",removeP);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="moje_menu"></div>
This is my solution i dont like them but works.
var arry = [];
arry = GM_listValues();
for ( var i = 0; i<arry.length; i++) {
// if(arry[i].search('player')==''){
document.getElementById('moje_menu').innerHTML += '<p class="lista_farm" id="'+arry[i]+'">'+arry[i]+'</p>';
//document.getElementById(arry[i]).onclick = usun_farme;
//}
}
var lista_farm = document.getElementsByClassName('lista_farm');
for(var i = 0; i<lista_farm.length; i++){
lista_farm[i].onclick = usun_farme;
}
I am wondering if there is a function I can use so that I can seperate data being called into groups of 6.
here is the long form of the code
var currentResults;
function init() {
getProducts();
}
function getProducts() {
$.ajax({
url:"php/products.php",
dataType: "json",
data: { public: true },
success:function(result){
processResults(result);
}
});
}
function processResults(results) {
currentResults = null;
if (!results && !results.products)
return;
currentResults = results.products;
for (var i = 0; i < results.products.length; i++) {
processResult(results.products[i]);
}
$(".galleryitem").click(handleThumbnailClick);
}
function processResult(result) {
var newDiv = '<div id="galleryitem' + result.id + '" class="galleryitem">';
newDiv += '<div class="imageHover" style="background: ' + result.color + '"> </div>';
newDiv += '<img class="galleryImage" src="' + encodeImagePath(result.thumbnail) + '" />';
if (result.artist)
newDiv += '<div class="imageArtist">' + result.artist + '</div>';
newDiv += '< /div>';
$('#gallery').append(newDiv);
}
i would like the function to be able to sort the images to groups of 6, something like this... (see areas at bottom with ***'s)
function processResult(result) {
var newDiv = '<div id="galleryitem' + result.id + '" class="galleryitem">';
newDiv += '<div class="imageHover" style="background: ' + result.color + '"> </div>';
newDiv += '<img class="galleryImage" src="' + encodeImagePath(result.thumbnail) + '" />';
if ***(!!first 6 called!!)***
newDiv += '<div class="imageArtist">' + result.artist + '</div>';
newDiv += '< /div>';
$('#galleryfirst').append(newDiv);
if ***(!!second 6 called!!)***
newDiv += '<div class="imageArtist">' + result.artist + '</div>';
newDiv += '< /div>';
$('#gallerysecond').append(newDiv);
}
Is doing something like this possible? Or does this whole code need an overhaul?
First, pass the index:
for (var i = 0; i < results.products.length; i++) {
processResult(results.products[i], i);
}
Then check it:
function processResult(result, index) {
var newDiv = ...
//check if the index is a multiple of 6
if(index % 6 == 0){
//do something every six results
}
HTH,
-Ted
Since you want to append the new items to different DIVs, the processResults function might be the better place to do this:
function processResults(results) {
var i = 0,
length = results.length,
first = $("#galleryfirst"),
second = $("gallerysecond");
first.append('<div class="imageArtist">' + results[0].artist + '</div>');
for (i; i < 6 && i < length; i++) {
processResult(results[i], first);
}
if (length > 6) {
second.append('<div class="imageArtist">' + results[6].artist + '</div>');
for (i = 6; i < 12 && i < length; i++) {
processResult(results[i], second);
}
}
}
function processResult(product, containerId) {
var newDiv = "...";
// build the HTML for newDiv...
$(containerId).append(newDiv);
}
I have two dynamic tables, one with the results of a sum and on other with the sum value, example: 4 and 2+2.
I have the following code in javascript where I click on the table with sum value, and then click on the respective sum value, and when I click on the right sum value, I want to know the value of the index on the column and row of the cell that was clicked.
I have eventListeners to create the clickable cells, and then compare with the cells of the other table.
Here is the code for the clickable cell of the first table:
var handler = function(e){if (choiceFlagElement != null) {
choiceFlagElement.style.background = 'green';
}
choiceFlagElement = e.target;
choiceFlagNumber = parseInt(e.target.innerHTML);
e.target.style.background = 'green';
}
and then I have this part for compare to the above cell:
var handler2 = function(e){
if (choiceFlagElement == null) {
return;
}
if (choiceFlagNumber == eval(e.target.innerHTML)) {
e.target.style.background = 'green';
e.target.style.visibility= 'hidden';
choiceFlagElement.style.visibility = 'hidden';
pontuacao();
inicio=Date.now();
count++;
choiceFlagNumber.target.innerHTML="-1";
}
}
Here is where I create the two table:
function criartabela(tamanho){
var tbl = "<table id=tabela>";
var tbl2 = "";
var resultados = new Array();
var f=0;
for (var ri = 0; ri < tamanho ; ri++) {
tbl += "<tr>";
for (var ci = 0; ci < tamanho; ci++) {
contas();
tbl += "<td class='cel"+tamanho+"' id=x visibility=visible >" + a + "+" + b + "</td>";
var total = a+b;
resultados[f]=total;
f=f+1;
}
}
resultados.sort(function(a,b){return a - b});
for(y=0; y<resultados.length; y++){
tbl2 += "<div class='resul"+tamanho+"' id=total >"+ resultados[y] + "</div>";
}
tbl += "</tr>";
tbl += "</table>";
document.getElementById("tabelap").innerHTML = tbl;
document.getElementById("resposta").innerHTML = tbl2;
}