Hello I have a piece of code that allows me to add an author.
I have a problem, I can't seem to delete the created node in my table
This is the worst frustration in my life. I could not seem to delete it.
I also have notice that every time I inspected the element I could not see the
new created element from the source. But when I view it on firebug I can actually see it there.
Adding an input element and appending it on the table works fine for me.
I am just very new to JavaScript and to this web thingy and deleting a CREATED ELEMENT via .createElement is where I am stuck at.
here is my code
<script>
var ctr = 1;
function showTextBox()
{
// is the table row I wanted to add the element before
var target = document.getElementById('bef');
var tblr = document.createElement('tr');
var tbld1 = document.createElement('td');
var tbld2 = document.createElement('td');
var tblin = document.createElement('input');
tblin.name = 'Author' + ctr;
tblin.id = 'Author' + ctr;
tblin.placeholder = 'add another author';
tbld1.appendChild( document.createTextNode('Author' + ctr ) );
tbld2.appendChild( tblin );
tblr.appendChild( tbld1 );
tblr.appendChild( tbld2 );
target.parentNode.insertBefore( tblr , target );
ctr++;
}
function hideTextBox()
{
var name = 'Author'+ctr;
var pTarget = document.getElementById('tbhold');
var cTarget = document.getElementById( name );
alert( cTarget ); // this one return null? Why? I have created id="Author1"
// viewing this code on source make the created elem to not appear
}
</script>
Am I doing something wrong? I really need help. This is for my project at school.
Is there any way I could delete it. I created that node and I want it to be deleted when I click something.
Also I prefer to stay with JS not with JQuery or other JStuff and I am disregarding compatibility for now because this is just a sample in my dummy form. I will deal on that later.
EDIT
In case you need the actual form here it is
<form enctype="multipart/form-data" action="process/" method="POST" />
<h3>Book Upload</h3>
<table border="2" id='tbhold'>
<tr>
<td>Title</td>
<td><input type="text" id="book_title" name="book_title" /></td>
</tr>
<tr>
<td>Author</td>
<td><input type="text" id="book_author" name="book_author" /></td>
</tr>
<tr id="bef">
<td colspan="2">
add author
remove
</td>
</tr>
</table>
</form>
Thank you very much!
Try this function:
function removeElements(elements){
for(var i = 0; i < elements.length; i++){
elements[i].parentNode.removeChild(elements[i]);
}
}
Then you can do this:
removeElements(document.querySelectorAll('#tbhold tr'));
function hideTextBox(){
var name = "Author" + (ctr - 1);
var pTarget = document.getElementById('tbhold');
var cTarget = document.getElementById(name);
var tr = cTarget.parentNode.parentNode;
tr.parentNode.removeChild(tr);
ctr = ctr - 1;
}
Here is a demo
every time I inspected the element I could not see the new created element from the source. But when I view it on firebug I can actually see it there.
If you change the DOM, you of course do not change the HTML source markup. Only the DOM inspector will show you the changes.
var name = 'Author'+ctr;
var cTarget = document.getElementById( name );
alert( cTarget ); // this one return null? Why? I have created id="Author1"
Yes, you created it using your showTextBox function. But that did also increment the ctr to 2, so that you now are looking for Author2 which obviously does not exist. So put a ctr--; before it and it should work.
Related
i have a site where i paste my entire source code into a box and update all the td tags with a background color if there isnt currently a "bgcolor" attribute.
I've been messing with this for some time but i can't get my ogSource to update. I've tried many ways such as assigning new variables, returns etc etc. No luck.
the below code properly scans for the appropriate td and adds the background color, it just doesnt apply it to the ogSource. I've removed all my other code to make this as basic as possible.
Can anyone assist with this?
Thanks in advance.
var ogSource = '<table id="test1"> <tr> <td> <table id="test2"> <tr> <td> </td> </tr> </table></td> </tr> </table>'
ogSource.replace(/\<td(.*?)\>/g, function(matches) {
if (!matches.includes('bgcolor')) {
var idx = matches.lastIndexOf(">");
if (idx > -1) {
matches = matches.substr(0, idx) + " bgcolor='pink'" + matches.substr(idx);
}
}
});
console.log(ogSource);
EDIT/UPDATE
After a lot of messing around- this was a solution that was able to capture all the source code pasted and make the modification needed.
ogSource = ogSource.replace(/\<td(.*?)\>/g, function( matches , i ) {
var idx = matches.lastIndexOf(">");
if (idx > -1) {
if (!matches.includes('bgcolor')) {
ogSource = matches.substr(0, idx) + " bgcolor='pink'" + matches.substr(idx);
} else {
ogSource = matches;
}
} return ogSource;
});
console.log(ogSource);
My initial answer was off the mark but quite a bit, however, I think regex in general may not be the best solution due to the amount of edge cases present and the DOMParser might be a better solution for this.
Essentially, you pass the html string into the DOMParser method parseFromString and store that in a variable, then select all td elements and check if they have a bgColor attribute, if they don't, give them one, then output the new DOM string.
Here's an example:
const domParser = new DOMParser();
const DOM = domParser.parseFromString(`<table id="test1"> <tr> <td> <table id="test2"> <tr> <td> </td> </tr> </table></td> </tr> </table>`, "text/html");
// Find all tds
const tds = DOM.querySelectorAll("td");
for(let i = 0; i < tds.length; i++) {
let currentTD = tds[i];
if(!currentTD.hasAttribute("bgColor")) {
currentTD.setAttribute("bgColor", "someValue");
}
}
console.log(DOM.body.innerHTML); // If you only want to return the table content
console.log(DOM.querySelector("html").innerHTML); // If you want all of the html code that was added
I am getting a Table from a database like this (row numbers may vary):
|Player 1|Player 2|
-------------------
|Danny |Danny |
|John |John |
|Mary |Mary |
I want to select two names, one from each Player column, and store them in two variables, say player1_id and player2_id which I will later use to insert data into the database. I also want to highlight the names when they are clicked. The highlight and the associated variable value should change when I click on another name.
For example, let's say I click on Danny and John from Player 1 and Player 2 respectively. These two names should get highlighted and the variables should get player1_id = "Danny" and player2_id = "John". If I change my mind and click on Mary on the Player 2 column, Mary should get highlighted, John should lose its highlight and player2_id should change to "Mary"
So far I managed to sort of getting only the highlight part (but when I click more than one names all stay highlighted). Could anyone point me to a correct direction, please?
Here is the JSFiddle code of what I have so far
try this: https://jsfiddle.net/dunsondog109/behcgwLf/7/
function inputClickHandler(e){
e = e||window.event;
var all = document.getElementsByTagName("td");
var tdElm = e.target||e.srcElement;
var tdIndex = tdElm.cellIndex;
var numberOfColumns = 2;
if(tdElm.style.backgroundColor == 'rgb(46, 204, 64)'){
tdElm.style.backgroundColor = '';
} else {
for (var i=0;i<all.length;i++) {
if (i%numberOfColumns==tdIndex%numberOfColumns) {
// It is in the same column
all[i].style.backgroundColor = '';
}
}
tdElm.style.backgroundColor = '#2ECC40';
}
}
You need to reset all the tds in your column first and then set the td that was clicked
maybe it will not help you, but this is what I created for fun ...
As I'm jQuery user I find it difficult to list the table for any actions using plain javascript ... I would prefer having list of players in some object, draw the table based on that list. Instead of adding css to table cell i would add class like active and then just easily remove / move that class to different player. Maybe even adding some classes or other data-attributes to the table cells to help identify correct row / cell ... Anyway, everything is possible, but with this design you will not get far with your project I think. Good luck.
var Game = function() {
var players = {};
var table = document.querySelector('#myTable');
var rows = table.querySelectorAll('tr');
function uncheckPlayers(col) {
for ( var i=0; i<rows.length; i++ ) {
var tds = rows[i].querySelectorAll('td');
for ( var x=0; x<tds.length; x++ ) {
if ( col === x ) {
tds[x].style.backgroundColor = '';
}
}
}
}
for ( var i=0; i<rows.length; i++ ) {
var tds = rows[i].querySelectorAll('td');
for ( var x=0; x<tds.length; x++ ) {
tds[x].addEventListener('click', function() {
var id = x;
return function() {
uncheckPlayers(id);
players[id] = new Player(id, this.innerText);
this.style.backgroundColor = 'red';
console.log(players);
}
}(x));
}
}
}
var Player = function(id, name) {
this.name = name;
this.id = id;
this.score = 0;
console.log(this);
};
var Game = new Game();
<html>
<head>
<title>Find table cell value on cell (table) click using JavaScript</title>
</head>
<body>
<center>
Click on table below to select Players.
<br />
<br />
</center>
<table align="center" id="myTable" border="1" style="cursor: pointer;">
<tr>
<th>Player 1</th><th>Player 2</th>
</tr>
<tr>
<td>Danny</td><td>John</td>
</tr>
<tr>
<td>John</td><td>Danny</td>
</tr>
<tr>
<td>Mary</td><td>Mary</td>
</tr>
</table>
<br />
</body>
</html>
Requirements
Add value to a field in one html page.
Submit.
Should show the value on another html page.
Any update on first page should update the second page and not open a new one.
I have written some HTML which is below. What is happening is that once I press submit it opens another page (page2.html) in same window. What I want is to have two html windows and whenever I update Home page it should reflect on the same page. (page2.html)
Home.html
<code>
<html>
<form target="_blank" type=get action="page2.html">
<table>
<tr>
<td>OrderID:</td>
<td><input type=text name=orderId size=10></td>
</tr>
<tr>
<td colspan=2><input type=submit value="Submit"></td>
</tr>
</table>
</form>
</html>
page2.html
<code>
<html>
<script LANGUAGE="JavaScript">
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["orderId"]);
document.write("OrderID = " + firstname + "<br>");
</script>
</html>
Initialize params to an empty object instead of an array:
var params = {};
That will allow you to use strings and other values for a key.
Be sure you include var when declaring variables:
var params = getParams();
var firstName = unescape(params["orderId"]);
It's fine for learning, but try to never use document.write. It's better to use: https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild. In this case, you can add it to the body by doing:
var p = document.createElement("p");
p.innerHTML = "OrderID = " + firstname;
document.body.appendChild(p);
Other then that, your code looks fine. Please comment if you're still having issues. Use firebug or chrome's console to post any errors.
I could achieve this by adding a target="page2.html" in the home.html
This is my first attempt in Javascript, so may be this is fairly easy question.
I need to access row element of a table, each row contains checkbox and two other column. If checkbox is checked, i need to get the id of checkbox.
I made following attempt but element_table.rows returns undefined, therefore i could not proceed. I debugged using Inspect element tool of eclipse and found element_table contains the rows.
Please suggest where I am making a mistake.
Javascript code:
function myfunction3(){
var element_table = document.getElementsByName('collection');
var element_tableRows = element_table.rows;
var selectedTr = new Array();
var data = "";
for(var i =0 ; element_tableRows.length;i++)
{
var checkerbox = element_tableRows[i].getElementsByName('checkmark');
if(checkerbox.checked){
selectedTr[selectedTr.length] = element_tableRows[i].getAttribute("name");
data = data + element_tableRows[i].getAttribute("name");
}
}
var element_paragraph = document.getElementsByName('description');
element_paragraph.innerHTML = data;
}
html code:
<table name="collection" border="1px">
<tr name="1">
<td><input type="checkbox" name="checkmark"></td>
<td>Tum hi ho</td>
<td>Arjit singh</td>
</tr>
<tr name="2">
<td><input type="checkbox" name="checkmark"></td>
<td>Manjha</td>
<td>Somesh</td>
</tr>
<tr name="3">
<td><input type="checkbox" name="checkmark"></td>
<td>Ranjhana</td>
<td>A.R Rehman</td>
</tr>
</table>
<input type="button" value="Check" onclick="myfunction3()">
here's a working version
function myfunction3(){
var element_table = document.getElementsByName('collection');
var element_tableRows = element_table[0].rows;
var selectedTr = new Array();
var data = "";
for(var i =0 ; i < element_tableRows.length;i++)
{
var checkerbox = element_tableRows[i].cells[0].firstChild;
if(checkerbox.checked){
//selectedTr[selectedTr.length] = element_tableRows[i].getAttribute("name"); //not sure what you want with this
data = data + element_tableRows[i].getAttribute("name");
}
}
var element_paragraph = document.getElementsByName('description');
element_paragraph.innerHTML = data;
alert(data);
}
http://jsfiddle.net/eZmwy/
jsfiddle for your example, your problem is mainly at when you getElementsByName you need to specify the index, also not that not all getElement methods are available in the table
i would also suggest you learn jQuery, this makes life easier, also not sure why you want to display the data as 1,2,3 the name on the tr... seems pretty strange to me
Actually this line
var element_table = document.getElementsByName('collection');
will return collection of elements. If you are sure that you have exactly one table with the specified name, try this approach:
var element_table = document.getElementsByName('collection')[0];
actually if you are using jQuery (very recommanded )
you can do something like
var idsArray = [];
$("[name=collection] tr td [type=checkbox]:checked").parent().each(function() {
idsArray .push($(this).attr('name'))
});
this answer related only to jQuery use (which is same as javascript only more compiled.)
The function simply injects new rows into an empty table when the function is called.
it would seem that since the <td> class gets assigned properly, that the <tr> would also get assigned... but it doesn't!
var newRow = document.createElement("tr");
for (data in dataArray)
{
var newName = document.createElement("td");
newName.className = classNames[data];
newName.innerHTML = dataArray[data];
newRow.appendChild(newName);
counter++;
}
document.getElementById("capturedData").appendChild(newRow);
var newRow2 = document.createElement("tr");
newRow2.class = "hiddenRow";
for (data in dataArray)
{
var newData = document.createElement("td");
var newDataField = document.createElement("input");
newDataField.type = "hidden";
newDataField.name = "name" + data;
newDataField.value = dataArray[data];
newData.class = classNames[data];
newData.value = dataArray[data];
newData.appendChild(newDataField);
newRow2.appendChild(newData);
}
which is really weird. All the newly added <td> elements have their classes assigned and they show up in the DOM. But the <tr> elements don't accept the class assignment and in the DOM they have no class.
Why is this? I've read about the purported asynchronicity of script execution, but surely this can't be the case, it would defeat the purpose, no?
DOM elements have no property class, because it is a reserved keyword. You are looking for className:
newRow2.className = "hiddenRow";
Same for the cell (newData). It works for your other cell because you are using className already:
newName.className = classNames[data];
Use only className, not class . There is no class-property in <TR>.