I'm trying to add a button in javascript file without using HTML bacsue I need to have it in the column inside the loop, but when I click on the button to call the function it shows the error that its looking on that button in HTML file!
how could I fix that?
function success(name) {
let info = "<div class='infoTable'>";
for (let i = 0; i < name.length; i++) {
info += "<div class='info'>";
info += "<div class='fcol'>" + (i+1) + "</div>";
info += "<div class='scol'>" + name[i].item + "</div>";
info += "<div class='fcol'>" + name[i].quantity + "</div>";
info += '<button onclick="deletee(\'' + name[i].ID + '\')"> Delete This<button />';
info += "</div>";
}
info += "</div>";
printItems.innerHTML = info;
}
this is the function
function deletee(id){
let url = "server/delete.php?id=" + id;
console.log(url);
fetch(url, { credentials: 'include' })
.then(response => response.text())
.then(getList)
}
this is the error
(index):1 Uncaught ReferenceError: deletee is not defined
at HTMLButtonElement.onclick ((index):1)
onclick # (index):1
The best solution in this case is using document.createElement: https://www.w3schools.com/jsref/met_document_createelement.asp
It's better practice than converting a string to DOM Elements.
Since you did not post all your code, we cannot assist further if we cannot see the function you are trying to execute.
The reason why I am suggesting using JS and not converting a string to DOM, is most IDE's will identify missing, misspelt, or incorrectly used functions. Which could've been your mistake.
Here is an example:
var colsToAdd = 5;
var rowsToAdd = 25;
function FillTable() {
//Get existing table or create a new one. Append to parent if create
var table = document.getElementById("testTable");
//Clear table
table.innerHTML = "";
//Create your rows using a for loop
for (var i = 0; i < rowsToAdd; i++) {
var row = document.createElement("TR");
table.appendChild(row);
//Create your columns using a for loop
for (var k = 0; k < colsToAdd; k++) {
{
var col = document.createElement("td");
row.appendChild(col);
if (k == colsToAdd - 1) {
var button = document.createElement("button");
button.type = "button";
//Button click event is an anonymous function
button.onclick =
function(r) {
return function() {
table.removeChild(r);
}
}(row)
button.innerHTML = "Delete";
col.appendChild(button);
} else {
col.innerHTML = "row " + i + " column " + k;
}
}
}
}
}
table {
border: 1px solid #000;
margin: 1em;
}
td {
border: 1px solid #000;
padding: 1em;
}
<div>
<h1>Heading</h1>
<button onclick="FillTable()">Fill table</button>
<table id="testTable">
</table>
</div>
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;
}
i want to create New Content. the New content is dataTable and will be saved to localStorage
When i click the ADD NEW TABLE button, the Table has created and saved to localStorage.
BUT
When im refresh the page, The table not display but saved to
localStorage.
MY JSFiddle
How to be able to display a table [datatable view] that has been created and stored in localStorage when the page is refreshed?
jQuery :
$("#mainTable").dataTable();
/* CREATE TABLE FITURE */
$('.submitButton').click(function() {
function getTableList() {
var addTable = '<div class="tab-pane" id="folder' + localStorage.Index + '">' +
'<div class="zf-table">' +
'<table id="table' + localStorage.Index + '" class="table table-bordered table-hover myFade">' +
'<thead>' +
'<tr>' +
'<th style="border-color:rgb(221, 221, 221);"></th>' +
'<th>Audience Name</th>' +
'<th>Type</th>' +
'<th>Size</th>' +
'<th>Date Created</th>' +
'<th>Action</th>' +
'</tr>' +
'</thead>' +
'</table>' +
'</div>' +
'</div>';
return addTable;
}
if (true) {
/** INDEX FOR INCREMENT ID **/
if (typeof(Storage) !== "undefined") {
if (localStorage.Index) {
localStorage.Index = Number(localStorage.Index) + 1;
} else {
localStorage.Index = 1;
}
} // if storage
var resultTable = JSON.parse(localStorage.getItem("tableList"));
if (resultTable == null) {
resultTable = [];
}
let newtableHTML = getTableList();
resultTable.push({
table: newtableHTML
});
// save the new resultTable array
localStorage.setItem("tableList", JSON.stringify(resultTable));
/* append Table baru */
$('.tab-content').append(newtableHTML);
var newTable = $("#table" + localStorage.Index).dataTable();
alert("sucess create table");
} else {
alert("Failed create Table");
}
}); // submitButton func
//on init fill the table-content
var resultTable = JSON.parse(localStorage.getItem("tableList"));
if (resultTable != null) {
//get the nav reference in DOM
let tableContent = $(".tab-content");
//clear the html contents
tableContent.html('');
for (var i = 0; i < resultTable.length; i++) {
var items = resultTable[i];
$(".tab-content").append(items.table);
}
} else {
let inititalTable = [];
inititalTable.push({
table: $('div.tab-content').html()
});
localStorage.setItem("tableList", JSON.stringify(inititalTable));
}
seems you forgot to call dataTable() on the table elements read from LocalStorage.
By looping through the stored tables with
for (var i = 0; i < resultTable.length; i++) {
var items = resultTable[i];
$(".tab-content").append(items.table);
}
you only append the initial HTML. It must be transformed by the dataTables plugin afterwards to show ordering, searching and paging features.
A possible solution would be calling dataTable() on all tables in tab-content container after the for loop:
for (var i = 0; i < resultTable.length; i++) {
var items = resultTable[i];
$(".tab-content").append(items.table);
}
$(".tab-content table").dataTable();
I am trying to allow clients to create a list of students then view more info by simply clicking on the button with the students name. I've got it to create the button and display the students name in the button but it only calls the function when I click submit to add the student to the list, the actual student button doesn't seem to function.
function updateStudentList() {
var html = "";
for (var i = 0; i < students.length; i++) {
html += "<li><button type='button' class='studentButton'" + "id=" + students[i].name +">" + students[i].name + "</button></li>";
}
$('#studentList').html(html);
for (var i = 0; i < students.length; i++) {
document.getElementById(students[i].name).addEventListener('click', openStudentInfo(students[i].name));
}
}
function openStudentInfo(studentName) {
console.log("Opening " + studentName + " info.");
var studentInfo = requestStudentByName(studentName);
if (studentInfo != null) {
var studentInfoForm = $("#studentInfoForm");
var html = "";
html += "<h3>Student Name: " + studentInfo.name + "</h3>";
html += "<h3>Student ID: " + studentInfo.studentID + "</h3>";
studentInfoForm.html(html);
$("#studentInfoModal").show();
}
}
HTML:
<ul data-role="listview" id="studentList"> </ul>
Note: I can't use the onclick tag in HTML, it causes security issues. Cordova also blocks this.
The way you binding the event is not ok. Try binding this way:
$(document).ready(function() {
$("#studentList").on("click", ".studentButton", function() {
var studentId = $(this).data("studentid");
openStudentInfo(studentId);
});
});
And in your HTML generation:
html += "<li><button type='button' class='studentButton' data-studentid='" + students[i].studentID +"'>" + students[i].name + "</button></li>";
This kind of event delagation works not metter how you create the elements inside the root element(studentList in this case), because the event was bound in it, and not on the dynamic elements.
no jquery version of DontVoteMeDown's answer
document.getElementById('studentList').addEventListener('click', function(event) {
var clickedEl = event.target;
if(clickedEl.className === 'studentButton') {
var studentId = clickedEl.dataset.studentId;
openStudentInfo(studentId);
}
});
I'm trying to figure out a way to retrieve and display the value of a div tag that is created with a 2D array using JavaScript. I figured either onclick or onmouseover would work but neither would in this approach. I would like to avoid creating 49 functions that does the same thing (just displaying the 'cell' the mouse is over).
<style type="text/css">
.float {float: left;}
.clear {clear:both;}
div {border: thin solid blue; padding: 2px;}
</style>
</head>
<body>
<div id="grid"></div>
<div id="bucket" class="float"></div>
</body>
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;
for (var i = 0; i < axisY; i++) {
for (var j = 0; j < axisZ; j++) {
document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(cellId)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
}
document.getElementById('grid').innerHTML += "<br class='clear' />";
}
function displayMe(cellId) {
// ???
}
function displayNone() {
document.getElementById('bucket').innerHTML = "";
}
</script>
Thanks!
You can simply get the cell id by passing this.id into the function.
Try this:
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;
for (var i = 0; i < axisY; i++) {
for (var j = 0; j < axisZ; j++) {
document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(this.id)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
}
document.getElementById('grid').innerHTML += "<br class='clear' />";
}
function displayMe(cellId) {
console.log(cellId);
}
function displayNone() {
document.getElementById('bucket').innerHTML = "";
}
</script>
Right now you have set up each cell element to call the function displayMe whenever the mouseover event occurs. When you call that function, you are passing the variable cellId as an argument. The problem is when that function is called, cellId is not defined. You can see this error pop up in your browser's developer console ("Uncaught ReferenceError: cellId is not defined").
You probably want to pass the cell element's id property, which you define dynamically here: id='area" + i + j + "'. You can use the id property of an element to look up the element (as you have done already), and get the text it contains via textContent.
To pass the cell element's id property, you need to use the this variable, like so: this.id. this will refer to the element that is triggering the event. So, if you change your onmouseover value of your div element to this: onmouseover='displayMe(this.id)', it will pass the appropriate value to your displayMe function, allowing you to do something like this:
function displayMe(cellId) {
document.getElementById('bucket').innerHTML = document.getElementById(cellId).textContent;
}
With these adjustments, your code will look like this in its entirety:
<style type="text/css">
.float {float: left;}
.clear {clear:both;}
div {border: thin solid blue; padding: 2px;}
</style>
</head>
<body>
<div id="grid"></div>
<div id="bucket" class="float"></div>
</body>
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;
for (var i = 0; i < axisY; i++) {
for (var j = 0; j < axisZ; j++) {
document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(this.id)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
}
document.getElementById('grid').innerHTML += "<br class='clear' />";
}
function displayMe(cellId) {
document.getElementById('bucket').innerHTML = document.getElementById(cellId).textContent;
}
function displayNone() {
document.getElementById('bucket').innerHTML = "";
}
</script>
I want to know how I change all the pre tags inside a document...
I'm using this:
var preContent = document.getElementById('code').innerHTML;
but this only changes the content of 1 pre tag... the one with the ID 'code'.
If you can show me how i can change all the pre tags using JavaScript I appreciate
Here's all the code:
window.onload = function () {
var preContent = document.getElementById('code').innerHTML;
var codeLine = new Array();
var newContent = '<table width="100%" border="1" '
+ 'cellpadding="0" cellspacing="0" >';
codeLine = preContent.split('\n');
for (var i = 0; i < codeLine.length; i++) {
newContent = newContent + '<tr><td class="codeTab1" >'
+ i.toString() + '</td><td class="codeTab2">'
+ codeLine[i] + '</td></tr>';
}
newContent = newContent + '</table>';
document.getElementById('code').innerHTML = newContent;
}
PS: This is to make a look like a normal compiler with numbers before the line
PPS: Each pre tag will have a different content and I want the same script to change it (if possible).
You can use getElementsByTagName:
var preElements = document.getElementsByTagName('pre');
for(var i = 0; i < preElements.length; ++ i)
{
var element = preElements[i];
/* modify element.innerHTML here */
}
First problem in you code . No two elements in a document can have same id .
So you can change it easily with jquery . look at the code .
$('pre').html("what ever text you want to show ");
Or with javascript you can do like this :
var x = document.getElementsByTagName('pre');
for(var i = 0; i < x.length; ++ i)
{
x.innerHTML = "what ever text you want to show";
}