White space in onclick value causes incorrect HTML - javascript

I am using below JavaScript code to append <tr> row to <table>:
<script type="text/javascript">
function addRow() {
var filesName = 'Document Draft.png'
var newRow = "<tr><td>td Data 1</td><td><a onclick=deleteDocument(this,'" + filesName + "')>Delete</a></td></tr>";
$("#idDocList").append(newRow);
}
</script>
This code adds one tr to table.
Problem: But the issue is that filesName has one white space which is wrongly render on DOM as below:
<tr>
<td>td Data 1</td>
<td>
<a onclick="deleteDocument(this,'Document" Draft.png')"">Delete</a>
</td>
</tr>
So the onclick doesn't work because rendered HTML is
onclick="deleteDocument(this,'Document" Draft.png')
As you can see in above line, it will take ( " ) instead of white space. How to fix it?

Since you have spaces in onclick property value, you should wrap its value with, for example, "":
...<a onclick=\"deleteDocument(this,'" + filesName + "')\">...
Fiddle example.
Instead of inline JS onclick="" (which is discouraged nowdays), you can use jQuery's .on("click"):
var filesName = 'Document Draft.png';
var newRow = "<tr><td>td Data 1</td><td><a class='delete'>Delete</a></td></tr>";
$("#idDocList").append(newRow);
$('#idDocList').on('click', ".delete", function()
{
deleteDocument(this, filesName);
});
Fiddle example.

Related

Passing js array as a parameter to dynamically created table row's onclick event function

I create a table dynamically and i want to pass js array to row;
var html= "<table id='tableID'><thead>...</thead><tbody></tbody></table>";
var jsArray = [{id: 1, val: "test"},{id: 2, val: "test2"}];
html+= '<tr onclick="myFunction('+jsArray+')"></tr>'
$('#tableID tbody').append(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableID">
<tbody></tbody>
</table>
I tried JSON.stringify(jsArray) then pass it but it doesn't work. Maybe I can change " with " but it doesn't looks best practice.
The reason JSON.stringify(jsArray) doesn't work is because the result includes double quotes, and as the value of the onclick attribute, it is put inside double quotes already. So, it should work if you use single quotes. Try changing onclick="..." to onclick='...'

How to make <td> clickable

I have created a table to display my SPARQL query result in the <td>, the result does display however I want it that when the<td> (result) is clicked on it displays a message box. Right now an extra <td> is displayed at the top and it only works for that particular one. Nothing seems to happen when clicking on the actual result <td>:
My code:
<table id="results">
<td class="td" onclick="myFunction()"></td>
</table>
<body>
<script type="text/javascript">
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX type: <http://dbpedia.org/class/yago/>
PREFIX prop: <http://dbpedia.org/property/>
SELECT ?country_name
WHERE {
?country rdf:type type:Country108544813.
?country rdfs:label ?country_name.
}
"Limit 1"
].join(" ");
alert("this query: [" + query + "]");
var queryUrl = url + "?query=" + encodeURIComponent(query) + "&format=json";
</body>
The JavaScript code I got it from an online material so still getting my head around it , the main use of it is to display the query result. So yeah answers are really appreciated and thanks for reading:)
So first off, your html is a little off... Your table is outside the tag, when it should be inside it: (note a td usually would be in a too)
<body>
<table id="results">
<tr><td class="td" onclick="myFunction()"></td></tr>
</table>
<script type="text/javascript">
....
But to your question more precisely: you have created one cell, and attached an onclick event handler to it and it only. The javascript code you grabbed actually appends new rows and cells to the table, and those don't have onclick handlers assigned.
So I'd try something like this instead:
<script type="text/javascript">
var table = $("#results");
table.on("click", "td", myFunction); // <-- magic!
var url = "http://dbpedia.org/sparql";
The "magic" line is the sweet part: it attaches the handler on the whole table, but filter the events by the "td" selector. Ideal when you are adding DOM elements dynamically...
And then you don't need to set your initial td, then one that is empty at the top of your table and clickable... Instead, just place an empty table on your page:
<body>
<table id="results"></table>
<script type="text/javascript">
....
Hope this helps!
While looking over your code you seam to only have the click event on the static
<table id="results">
<td class="td" onclick="myFunction()"></td>
</table>
When you add the dynamical the is no class or onclick event. You can fix this by either adding the onclick to the td dynamically or running a script that sets all the tds in that table to have the same click event.
function getTableCell(fieldName, rowData) {
//var td = $("<td></td>");
var td = $("<td class="td" onclick="myFunction()"></td>");
var fieldData = rowData[fieldName];
//alert("fieldName = ["+fieldName +"] rowData[fieldName][value] = ["+rowData[fieldName]["value"] + "]");
td.html(fieldData["value"]);
return td;
}
or
$("#results td").click(function(){
var x;
if (confirm("Press a button!") == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
}

Styling HTML with Javascript based on values

I am trying to style an HTML table row based on values in that row, but I am stuck on step 1 - styling it at all!
Here's the code I have:
<tr id="tablerow<%=j%>">
<script type="text/javascript">
document.getElementById("tablerow<%=j%>").style.backgroundColor = "red";
</script>
<%=j> is pulling a row number in from the loop that's loading the data from the Access database as it loads the table.
The table rows are not showing up as red!
Then later I am going to use some IF statements in Javascript to color the rows based on data from some of the elements:
var datecheck = new Date;
if (document.getElementById("confirmStatus<%=j%>").value=="P" && (document.getElementById("confirmYear<%=j%>").value < datecheck.getFullYear())) {
document.getElementById("tablerow<%=j%>").style.backgroundColor = "LightCoral"; }
I was able to figure it out - thanks for the help!
Have you checked your JavaScript console?
Atleast it should be document.getElementById not document.getElementByID
Your script execute too early - html not ready yet. Try
<tr id="tablerow<%=j%>">
<script type="text/javascript">
window.addEventListener('load',function(){
document.getElementByID("tablerow<%=j%>").style.backgroundColor = "red";
}
</script>
But it's ugly idea do it by js
I find it better to use custom attributes instead of string concatenation:
<tr data-dbid="<%=j%>" style="background-color:red">
<td><input class="confirmYear" /></td>
<td><input class="confirmStatus" /></td>
</tr>
Then use that when needed:
function checkRow(id) {
var _tr = document.querySelector("[data-dbid=" + id + "]"),
_confirmYear = _tr.querySelector(".confirmYear"),
_confirmStatus = _tr.querySelector(".confirmStatus");
if (_confirmYear.value === "P" && _confirmStatus.value < datecheck.getFullYear())
_tr.style.backgroundColor = "LightCoral";
}
window.addEventListener('load',function(){
[].forEach.call(
document.querySelectorAll("[data-dbid]"),
function(el) { checkRow(el.dataset["dbid"]) }
);
});

How to delete specific textarea field?

I have a dynamic form that is generated based on javascript. Here's the relevant javascript:
function addRowToTable()
{
var tbl = document.getElementById('convention');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// right cell
var cellRight = row.insertCell(0);
var el = document.createElement('textarea');
el.rows = '2';
el.cols = '80';
el.name = 'conventionSkill' + iteration;
el.size = 40;
var el2 = document.createElement('input');
el2.type = 'hidden';
el2.name = 'conventioni_alt';
el2.value = iteration;
el2.size = 40;
el.onkeypress = keyPressTest;
cellRight.appendChild(el);
cellRight.appendChild(el2);
}
function removeRowFromTable()
{
var tbl = document.getElementById('convention');
var lastRow = tbl.rows.length;
if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
HTML:
<table id="convention">
<tr>
<td><label>Skill Descriptions:</label></td>
</tr>
<tr>
<td>
<textarea name='convention_54' rows='2' cols='80'>
text
</textarea></td>
<td><a href='javascript:void(0)' onclick='removeRowFromTable(54);'><font size=
'+1'>-</font></a></td>
</tr>
<tr>
<td>
<textarea name='convention_55' rows='2' cols='80'>
text2
</textarea></td>
<td><a href='javascript:void(0)' onclick='removeRowFromTable(55);'><font size=
'+1'>-</font></a></td>
<td><a href='javascript:void(0)' onclick='addRowToTable();'><font size=
'+1'>+</font></a></td>
</tr>
</table>
I like the add function as it simply adds a new textarea. However, the remove button removes from the bottom of the form up. How can I make it so that removeRowFromTable removes a specific textarea? For example, if I want to delete one of the textareas in the middle, rather than the last one in the form.
Thanks for any suggestions!
In short, you'll have to find the exact textarea you want to remove (probably by ID).
However, before you go too far down this road hand-rolling ID enumeration and DOM manipulation code, you might want to look at jQuery (http://jquery.com/). jQuery handles oodles of this stuff quite easily via its selector mechanism and will save you from many of the cross-browser headaches you may have if you try to do all this DOM manipulation yourself.
You'll find a lot of questions about jQuery on SO; for example look at how easy this related- and-simple table manipulation is:
What is the best way to remove a table row with jQuery?
IMHO learning jQuery was a tremendous Javascript productivity boosts for me and my team -- it's well worth the time spent in my experience.

Javascript: Can't find newly added form inputs in the DOM

I can only assume I'm doing something wrong, because when I step through the javascript it can't find the object at all.
What I'm trying to do is dynamically add rows of combo boxes to the table. The combo box code is more-or-less irrelevant, because trying to find the newly-generated inputs in the DOM by going through the form doesn't seem to work. I'm not sure if they even exist.
First, I have the form itself:
<form name="WEB070EDIT" action="WEB070" method="POST">
Then lower, there's the table that will contain the generated cells:
<table id='Form2Section2' width="100%" border=0 cellspacing=0 cellpadding=2>
<tr class="woborder">
<th >5. Material or Process Name</th>
<th >6. Specification Number</th>
<th >7. Code</th>
<th >8. Special Process Supplier Code</th>
<th >9. Customer Approval Verification</th>
<th >10. Certificate of Conformance Number</th>
</tr>
</table>
A bit above, there is my heinous script function that populates the table:
<script type="text/javascript">
function addForm1(itemId)
{
if (typeof addForm1.counter == 'undefined') {
addForm1.counter = 1;
}
var object = document.getElementById(itemId);
var curRow = object.insertRow(-1);
curRow.className = "woborder";
curRow.style.backgroundColor = "#D0D0D0";
var curCell = curRow.insertCell(-1);
var cellElem = document.createElement("text");
cellElem.size = 25
cellElem.value = ""
cellElem.name = "V_P2_MATERIAL_" + addForm1.counter;
cellElem.id = "V_P2_MATERIAL_"+ addForm1.counter;
var newAttr = document.createAttribute("onKeyUp");
newAttr.nodeValue = "...[some lengthy script stuff trimmed for readability]...";
cellElem.setAttributeNode(newAttr);
curCell.appendChild(cellElem);
curCell.appendChild(document.createElement("br"));
cellElem = document.createElement("hidden");
cellElem.name = "P2_MATERIAL_" + addForm1.counter;
cellElem.id = "P2_MATERIAL_" + addForm1.counter;
cellElem.value = "";
curCell.appendChild(cellElem);
cellElem = document.createElement("select");
cellElem.name = "MYSELECT_P2_MATERIAL_" + addForm1.counter;
cellElem.id = "MYSELECT_P2_MATERIAL_" + addForm1.counter;
cellElem.size = 10;
newAttr = document.createAttribute("onClick");
newAttr.nodeValue = "...[more script stuff here we don't care about]...";
eval("document.getElementById('V_P2_MATERIAL_" + addForm1.counter + "').focus();");
eval("combohandleKeyUp('WEB070EDIT','MYSELECT_P2_MATERIAL_" + addForm1.counter + "','V_P2_MATERIAL_" + addForm1.counter + "','P2_MATERIAL_" + addForm1.counter + "',MYLIST_P2_MATERIAL,MYDESCLIST_P2_MATERIAL,9999999);");
}
</script>
The reason we don't care about the onClick and onKeyUp is because we never get to that point. What's supposed to happen is that the eval() is supposed to run some javascript that populates the combo boxes with some predefined variables. It works perfectly, as long as the inputs are static. However, when I hit the button that runs this script, it pukes on that combohandleKeyUp right near the beginning, where it is supposed to find the following object:
document.forms['WEB070EDIT'].elements["P2_MATERIAL_1"]
Obviously this is all variables inside the script itself, but that's what it parses out to according to the debugger.
When I use Firebug's DOM inspector, I can find the forms, I can find WEB070EDIT, but I can't find the hidden input P2_MATERIAL_1. The static stuff's all in there, but nothing that's getting dynamically generated. Does this simply not work with dynamic objects? Am I missing something? Am I building it completely wrong?
I see various issues in here.
I don't understand why you're using eval(). The things that you're eval-ing could be just called as plain old JavaScript. The first eval() can be dropped and replaced by a simple .focus() call on the element as soon as it is added to the DOM.
What do you expect this to do?
document.createElement("text");
That creates a <text> tag in the HTML but that's not a valid tag. Are you trying to do something like this?
document.createElement("input");
cellElem.type = 'text';
//...
You're setting a size attribute so I'm guessing that you're trying to produce <input type="text" .../>.
You are initializing addForm1.counter but you never increment it. You'll end up with duplicate IDs that way and that leads to the gnashing of teeth and sundry sorts of confusion.
You create a <select>:
cellElem = document.createElement("select");
and then throw it away as you neglect to add it to the DOM. You also create an onClick attribute right after the <select> but you didn't add it to anything.
I stripped your code down a bit and added some things you were missing, seems to work just fine: http://jsfiddle.net/ambiguous/3v6R3/

Categories