I have developed a mobile webpage using HTML5+JS. I added a button dynamically to webpage. But when i added onclick functionality to that button, it's not working.
My Html code is;
<head><script>
var myarray = ['a','b','c','d','e','f'];
var arr = document.getElementById('content');
for(i=0;i<myarray.length;i++)
{
var table = document.createElement('table');
table.className = 'table';
var tr = document.createElement('tr');
var td = document.createElement('td');
var Btn = document.createElement('input');
Btn.type = 'button';
Btn.className = 'Btn';
Btn.value = 'VOTE';
Btn.id = myarray[i];
Btn.onclick = function(){
alert("You have Selected" + " " + this.id);
};
td.appendChild(Btn);
tr.appendChild(td);
table.appendChild(tr);
arr.appendChild(table);
}
</script>
<style>
.table { width:100%;height:70px;}
.Btn { margin-top:3px;border-radius:0;font-size:15px;height:30px;width:100px; color:#FFFFFF; margin-left:auto;margin-right:auto;display:block; }
</style></head>
<body><section id='content'></section></body>
It's not the onclick that's the problem. The problem is you are trying to get the #content element before it is loaded/rendered.
The solution is to wrap the code in window.onload which ensures the code will only execute when the elements in the page are loaded and ready for use:
window.onload = function () {
var myarray = ['a', 'b', 'c', 'd', 'e', 'f'];
var arr = document.getElementById('content');
for (i = 0; i < myarray.length; i++) {
var table = document.createElement('table');
table.className = 'table';
var tr = document.createElement('tr');
var td = document.createElement('td');
var Btn = document.createElement('input');
Btn.type = 'button';
Btn.className = 'Btn';
Btn.value = 'VOTE';
Btn.id = myarray[i];
Btn.onclick = function () {
alert("You have Selected" + " " + this.id);
};
td.appendChild(Btn);
tr.appendChild(td);
table.appendChild(tr);
arr.appendChild(table);
}
};
The problem is your code is not running on dom ready
window.onload = function (){
var myarray = ['a','b','c','d','e','f'];
var arr = document.getElementById('content');
for(i=0;i<myarray.length;i++)
{
var table = document.createElement('table');
table.className = 'table';
var tr = document.createElement('tr');
var td = document.createElement('td');
var Btn = document.createElement('input');
Btn.type = 'button';
Btn.className = 'Btn';
Btn.value = 'VOTE';
Btn.id = myarray[i];
Btn.onclick = function(){
alert("You have Selected" + " " + this.id);
};
td.appendChild(Btn);
tr.appendChild(td);
table.appendChild(tr);
arr.appendChild(table);
}
}
Demo: Plunker
Related
I'm developing a test build for my project, which includes a lot of data manipulation. I have two buttons inline at the end of the rows, one for editing, and one for committing the changes made.
function editRow(btn) {
var row = btn.parentNode.parentNode;
row.contentEditable = "true";
row.focus();
}
function addRow(tableID, numberOfCells) {
var tbl = document.getElementById(tableID);
//create rows
var newRow = tbl.insertRow(-1);
var i;
for (i = 0; i < numberOfCells; i++) {
newRow.insertCell(0);
}
//assignbuttons
var lastcell = newRow.cells[numberOfCells - 1];
addEditButton(lastcell);
addCommitButton(lastcell);
}
function addEditButton(context) {
var button = document.createElement("input");
button.type = "button";
button.value = "Edit";
button.onclick = editRow(this);
context.appendChild(button);
}
The user will press the new row button, and then an empty row will appear along with the two buttons.
I am getting the error:
Uncaught TypeError: Cannot read property 'parentNode' of undefined
at editRow (js.js:97)
at addEditButton (js.js:123)
at addRow (js.js:115)
at HTMLButtonElement.onclick (index.html:36)
There are 2 problems I can see.
button.onclick = editRow(this); the this would result in undefined (in strict mode) in that scope. You can probably fix this by sending in the button element
button.onclick = editRow(button);
More reading on this in a function scope
Also you are not creating a row with a td element to place the button in. So btn.parentNode.parentNode is not the row element as you are expecting
Try this
function editRow(btn) {
var row = btn.parentNode.parentNode;
row.contentEditable = "true";
row.focus();
}
function addRow(tableID, numberOfCells) {
var tbl = document.getElementById(tableID);
//create rows
var newRow = tbl.insertRow(-1);
var i;
for (i = 0; i < numberOfCells; i++) {
newRow.insertCell(0);
}
//assignbuttons
var lastcell = newRow.cells[numberOfCells - 1];
addEditButton(lastcell);
//addCommitButton(lastcell);
}
function addEditButton(context) {
var row = document.createElement("row");
var td = document.createElement("td");
var button = document.createElement("input");
button.type = "button";
button.value = "Edit";
td.appendChild(button);
row.appendChild(td);
context.appendChild(row);
button.onclick = editRow(button);
}
addRow("myTable", 2)
<table id="myTable">
</table>
function addRow(tableID, numberOfCells) {
var tbl = document.getElementById(tableID);
var tableHTML = $("#" + tableID).html();
if(numberOfCells === 5) {
$("#" + tableID).html(tableHTML + "<tr id=\"bikeTableBike_new\"><td>-</td><td>-</td><td>-</td><td>-</td><td><button id=\"editBikeButton\" class=\"tableButtons\" onclick=\"editRow(this)\"><img src=\"images/edit.png\"/></button><button id=\"deleteBikeButton\" class=\"tableButtons\" onclick=\"commitRow(this)\"><img src=\"images/commit.png\"/></button></td></tr>");
}
if(numberOfCells === 4) {
$("#" + tableID).html(tableHTML + "<tr id=\"bikeTableBike_new\"><td>-</td><td>-</td><td>-</td><td><button id=\"editBikeButton\" class=\"tableButtons\" onclick=\"editRow(this)\"><img src=\"images/edit.png\"/></button><button id=\"deleteBikeButton\" class=\"tableButtons\" onclick=\"commitRow(this)\"><img src=\"images/commit.png\"/></button></td></tr>");
}
if(numberOfCells === 3) {
$("#" + tableID).html(tableHTML + "<tr id=\"bikeTableBike_new\"><td>-</td><td>-</td><td><button id=\"editBikeButton\" class=\"tableButtons\" onclick=\"editRow(this)\"><img src=\"images/edit.png\"/></button><button id=\"deleteBikeButton\" class=\"tableButtons\" onclick=\"commitRow(this)\"><img src=\"images/commit.png\"/></button></td></tr>");
}
}
Let me start by saying, I have seen very similar questions and yes; I have read through and tried to implement the suggested solutions. I am trying to have it so that only one checkbox in a row can be selected at a time. The most common answer I have seen is this one;
$('input.example').on('change', function() {
$('input.example').not(this).prop('checked', false);
});
This solution did work for me, but that was before I was creating my table dynamically. Here is my code currently. It is pulling the table data from a MySQL table via a JSON $.post.
function load() {
$.post(
"Returnsmedb.php",
function(response) {
var block = []
index = 0;
for (var item in response) {
var objectItem = response[item];
var firstname = objectItem.fname;
var lastname = objectItem.lname;
var username = objectItem.uname;
var email = objectItem.email;
var password = objectItem.password;
var deny = document.createElement("input");
deny.type = "checkbox";
deny.className = "chk";
deny.name = "deny";
deny.id = "deny";
var approve = document.createElement("input");
approve.type = "checkbox";
approve.className = "chk";
approve.name = "approve";
var moreinfo = document.createElement("input");
moreinfo.type = "checkbox";
moreinfo.className = "chk";
moreinfo.name = "moreinfo";
block.push(firstname);
block.push(lastname);
block.push(username);
block.push(email);
block.push(password);
block.push(deny);
block.push(approve);
block.push(moreinfo);
dataset.push(block);
block = [];
}
var data = [" First Name", " Last Name ", " User Name ", " Email ", "Password", " Deny", "Approve", "More Information"]
tablearea = document.getElementById('usersTable');
table = document.createElement('table');
thead = document.createElement('thead');
tr = document.createElement('tr');
for (var i = 0; i < data.length; i++) {
var headerTxt = document.createTextNode(data[i]);
th = document.createElement('th');
th.appendChild(headerTxt);
tr.appendChild(th);
thead.appendChild(tr);
}
table.appendChild(thead);
for (var i = 0; i < dataset.length; i++) {
tr = document.createElement('tr');
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td')); //Added for checkbox
tr.appendChild(document.createElement('td')); //Added for checkbox
tr.appendChild(document.createElement('td')); //Added for checkbox
tr.cells[0].appendChild(document.createTextNode(dataset[i][0]));
tr.cells[1].appendChild(document.createTextNode(dataset[i][1]));
tr.cells[2].appendChild(document.createTextNode(dataset[i][2]));
tr.cells[3].appendChild(document.createTextNode(dataset[i][3]));
tr.cells[4].appendChild(document.createTextNode(dataset[i][4]));
tr.cells[5].appendChild((dataset[i][5])); //
tr.cells[6].appendChild((dataset[i][6])); //
tr.cells[7].appendChild((dataset[i][7])); //
table.appendChild(tr);
}
tablearea.appendChild(table);
}, 'json'
);
}
I have tried pasting the common solution in various areas but I still cannot get it to work. Any help would be greatly appreciated.
Thanks!
Please try this code
$('input.chk').on('change', function() {
if($('this:checked'))
{
var tr =$(this).parents('tr');
tr.find("input.chk").not(this).each(function(){
$(this).prop('checked', false);
});
}
});
Here, I'm generating table by creating td's and tr's by clicking buttons, how can I add event listener to every td, and when it's clicked I can know the tr where this td placed.
var table = document.createElement('table');
document.body.appendChild(table);
var tr = document.createElement('tr');
table.appendChild(tr);
var td = document.createElement('td');
tr.appendChild(td);
var createTd = document.createElement('button');
createTd.innerHTML = 'Create td';
document.body.appendChild(createTd);
var createTr = document.createElement('button');
createTr.innerHTML = 'Create tr';
document.body.appendChild(createTr);
createTd.addEventListener('click',function() {
td = document.createElement('td');
tr.appendChild(td);
})
createTr.addEventListener('click',function() {
tr = document.createElement('tr');
table.appendChild(tr);
})
You can add it
var createTd = document.createElement('button');
createTd.innerHTML = 'Create td';
createTd.onclick = function() {
// to do something
};
document.body.appendChild(createTd);
var createTr = document.createElement('button');
createTr.innerHTML = 'Create tr';
createTr.onclick = function() {
// to do something
};
document.body.appendChild(createTr);
I'm working on a challenge that requires I only use Javascript (no jQuery). I created an HTML with twelve different buttons and an heading at the bottom. I want to switch the heading with the buttons text on click but mostly receive the error "Uncaught TypeError: Cannot set property 'innerHTML' of null/undefined."
I included the whole script, and I know my createHTML function could use some cleaning up, but I only included it so you can see how I added the click handler. switchHeading function is at the bottom.
function createHTML(){
var container = document.getElementsByClassName("container");
//add div "row"
var row = document.createElement("div");
row.className = "row";
container[0].appendChild(row);
//add div "col"
var col = document.createElement("div");
col.className = "col-md-12";
row.appendChild(col);
//add star button
var starButton = document.createElement("button");
starButton.className = "btn btn-default btn-lg";
starButton.setAttribute("type", "button");
starButton.onclick = switchHeading();
col.appendChild(starButton);
starButton.appendChild(document.createTextNode("Star"));
//add hr
var hr = document.createElement("hr");
col.appendChild(hr);
//add div
var div = document.createElement("div");
col.appendChild(div);
//add btn group
var btnGroup = document.createElement("div");
btnGroup.className = "btn-group";
div.appendChild(btnGroup);
//add num btns
for(var i=1; i<5; i++){
var numButton = document.createElement("button");
numButton.className="btn btn-default";
numButton.setAttribute("type", "button");
numButton.onclick = switchHeading();
btnGroup.appendChild(numButton);
numButton.appendChild(document.createTextNode(i));
}
//add btn group2
var btnGroup2 = document.createElement("div");
btnGroup2.className = "btn-group";
div.appendChild(btnGroup2);
//add some more num buttons
for(var i=5; i<8; i++){
var numButton = document.createElement("button");
numButton.className="btn btn-default";
numButton.setAttribute("type", "button");
numButton.onclick = switchHeading();
btnGroup2.appendChild(numButton);
numButton.appendChild(document.createTextNode(i));
}
//add 8 button
var btnGroup3 = document.createElement("div");
btnGroup3.className ="btn-group";
div.appendChild(btnGroup3);
var ochoButton = document.createElement("button");
ochoButton.className = "btn btn-default";
ochoButton.setAttribute("type", "button");
ochoButton.onclick = switchHeading();
btnGroup3.appendChild(ochoButton);
ochoButton.appendChild(document.createTextNode(8));
//2nd hr
var hr2 = document.createElement("hr");
col.appendChild(hr2);
//Anotha div
var anotherDiv = document.createElement("div");
col.appendChild(anotherDiv);
//last btn group
var btnGroupLg = document.createElement("div");
btnGroupLg.className = "btn-group btn-group-lg";
anotherDiv.appendChild(btnGroupLg);
//LMR buttons
var LButton = document.createElement("button");
LButton.className = "btn btn-default";
LButton.setAttribute("type", "button");
LButton.onclick = switchHeading();
btnGroupLg.appendChild(LButton);
LButton.appendChild(document.createTextNode("Left"));
var MButton = document.createElement("button");
MButton.className = "btn btn-default";
MButton.setAttribute("type", "button");
MButton.onclick = switchHeading();
btnGroupLg.appendChild(MButton);
MButton.appendChild(document.createTextNode("Middle"));
var RButton = document.createElement("button");
RButton.className = "btn btn-default";
RButton.setAttribute("type", "button");
RButton.onclick = switchHeading();
btnGroupLg.appendChild(RButton);
RButton.appendChild(document.createTextNode("Right"));
//add h3
var h3 = document.createElement("h3");
h3.id = "heading";
anotherDiv.appendChild(h3);
h3.appendChild(document.createTextNode("Click a Button!"));
};
createHTML();
function switchHeading() {
var content = this.innerHTML;
var h3 = document.getElementsByTagName('h3');
h3[0].innerHTML = content;
}
Make sure you've got h3 tag on your page and get rid of parentheses in
RButton.onclick = switchHeading();
The parentheses make function switchHeading() run immediately wich leads to undefined result since switchHeading() has no return value. This works:
<html>
<div class="container"></div>
<h3>Hello</h3>
<script>
function createHTML(){
var container = document.getElementsByClassName("container");
//add div "row"
var row = document.createElement("div");
row.className = "row";
container[0].appendChild(row);
//add div "col"
var col = document.createElement("div");
col.className = "col-md-12";
row.appendChild(col);
//add star button
var starButton = document.createElement("button");
starButton.className = "btn btn-default btn-lg";
starButton.setAttribute("type", "button");
starButton.onclick = switchHeading;
col.appendChild(starButton);
starButton.appendChild(document.createTextNode("Star"));
//add hr
var hr = document.createElement("hr");
col.appendChild(hr);
//add div
var div = document.createElement("div");
col.appendChild(div);
//add btn group
var btnGroup = document.createElement("div");
btnGroup.className = "btn-group";
div.appendChild(btnGroup);
//add num btns
for(var i=1; i<5; i++){
var numButton = document.createElement("button");
numButton.className="btn btn-default";
numButton.setAttribute("type", "button");
numButton.onclick = switchHeading;
btnGroup.appendChild(numButton);
numButton.appendChild(document.createTextNode(i));
}
//add btn group2
var btnGroup2 = document.createElement("div");
btnGroup2.className = "btn-group";
div.appendChild(btnGroup2);
//add some more num buttons
for(var i=5; i<8; i++){
var numButton = document.createElement("button");
numButton.className="btn btn-default";
numButton.setAttribute("type", "button");
numButton.onclick = switchHeading;
btnGroup2.appendChild(numButton);
numButton.appendChild(document.createTextNode(i));
}
//add 8 button
var btnGroup3 = document.createElement("div");
btnGroup3.className ="btn-group";
div.appendChild(btnGroup3);
var ochoButton = document.createElement("button");
ochoButton.className = "btn btn-default";
ochoButton.setAttribute("type", "button");
ochoButton.onclick = switchHeading;
btnGroup3.appendChild(ochoButton);
ochoButton.appendChild(document.createTextNode(8));
//2nd hr
var hr2 = document.createElement("hr");
col.appendChild(hr2);
//Anotha div
var anotherDiv = document.createElement("div");
col.appendChild(anotherDiv);
//last btn group
var btnGroupLg = document.createElement("div");
btnGroupLg.className = "btn-group btn-group-lg";
anotherDiv.appendChild(btnGroupLg);
//LMR buttons
var LButton = document.createElement("button");
LButton.className = "btn btn-default";
LButton.setAttribute("type", "button");
LButton.onclick = switchHeading;
btnGroupLg.appendChild(LButton);
LButton.appendChild(document.createTextNode("Left"));
var MButton = document.createElement("button");
MButton.className = "btn btn-default";
MButton.setAttribute("type", "button");
MButton.onclick = switchHeading;
btnGroupLg.appendChild(MButton);
MButton.appendChild(document.createTextNode("Middle"));
var RButton = document.createElement("button");
RButton.className = "btn btn-default";
RButton.setAttribute("type", "button");
RButton.onclick = switchHeading;
btnGroupLg.appendChild(RButton);
RButton.appendChild(document.createTextNode("Right"));
//add h3
var h3 = document.createElement("h3");
h3.id = "heading";
anotherDiv.appendChild(h3);
h3.appendChild(document.createTextNode("Click a Button!"));
};
createHTML();
function switchHeading() {
var content = this.innerHTML;
var h3 = document.getElementsByTagName('h3');
h3[0].innerHTML = content;
}
</script>
</html>
Actually i am beginner in javascript and i am making a todo list with only javascript and given is my code..
function updateItemStage() {
var cbId = this.id.replace("cb_", "");
var itemText = document.getElementById("Item_" + cbId);
if (this.checked) {
itemText.className = "checked";
} else {
itemText.className = "";
}
}
function addNewItem(list, itemText) {
totalItems++;
var listItem = document.createElement("li");
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.onclick = updateItemStage;
checkBox.id = "cb_" + totalItems;
var span = document.createElement("span");
span.innerHTML = itemText;
span.id = "Item_" + totalItems;
listItem.appendChild(checkBox);
listItem.appendChild(span);
list.appendChild(listItem);
}
var totalItems = 0;
var btnNew = document.getElementById("btnAdd");
btnNew.onclick = function() {
var todoInput = document.getElementById("todoInput")
var itemText = todoInput.value;
if(!itemText || itemText == "") {
return false;
}
addNewItem(document.getElementById("todolist"), itemText);
};
Using this code i successfully create a todo list but in this code i didn't get what is the main role and work of this keyword..
can anyone help me please to understand this problem ???????????
The this keyword is the element where your event happens
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.onclick = updateItemStage;
In your case, this is the checkBox which you clicked.