Issue while passing a value from a link to a JS file - javascript

I have the table data which is displyaed like below, where Dispute Number has a link.
I have generated the html code using the function below
getMessage(result){
for (var j = 0; j < result.invocationResult.resultSet.length; j++) {
var tmp = "<tr>";
var resSet = result.invocationResult.resultSet[j];
for(res in resSet){
if(res=="DISP_NUMBER")
var ab = resSet.DISP_NUMBER;
tmp += "<td><a href="+"#"+" data-role="+" button"+" id="+" button-mainpage" +" onclick="+ " changeToSomePage("+ab+");>"+ab +"</a></td>";
$("#mytable").append(tmp+"</tr>");
When the user clicks on the dispute number link, the below js function gets called.
I am passing the dispute number with the variable 'ab'. When i alert this value in the function changeToSomePage(ab),
it works sometimes, sometimes it giving incorrect number.
function changeToSomePage(ab) {
alert(ab);
$('#pagePort').load("pages/disputedetails.html");
}
Do you see anything wrong with the above code ? Is this the right apporach to retrieve the value from a link & send it to a JS function when clicked ??
Thanks..Johnson

It looks like ab is a string. You need to wrap it with quotes.
"<td><a href="+"#"+" data-role="+" button"+" id="+" button-mainpage" +" onclick="+ " changeToSomePage(\""+ab+"\");>"+ab +"</a></td>";
Of course inline handlers are not the best way. You can use event delegation instead: bind single onclick handler on the table itself.
$('#mytable').on('click', '.change-to-some-page', function() {
var num = $(this).data('num');
});
And when generating rows.
tmp += '<td><a href="#" data-role="button" class="change-to-some-page" ' +
'data-num="' + ab + '">' +ab +'</a></td>';

rewrite this
"<td><a href="+"#"+" data-role="+" button"+" id="+" button-mainpage" +" onclick="+ " changeToSomePage("+ab+");>"+ab +"</a></td>"
using double and single quotes - much easier to read. and create unique ids ith the j value
"<td><a href='#' data-role='button' id='button-mainpage-" + j + "' onclick=' changeToSomePage("+ab+");'>"+ab +"</a></td>"

Related

Passing argument to on click event of dynamically generated element

I am trying to pass arguments to onclick event of dynamically generated element. I have already seen the existing stackoveflow questions but it didn't answer my specific need.In this existing question , they are trying to access data using $(this).text(); but I can't use this in my example.
Click event doesn't work on dynamically generated elements
In below code snippet, I am trying to pass program and macroVal to onclick event but it doesn't work.
onClickTest = function(text, type) {
if(text != ""){
// The HTML that will be returned
var program = this.buffer.program;
var out = "<span class=\"";
out += type + " consolas-text";
if (type === "macro" && program) {
var macroVal = text.substring(1, text.length-1);
out += " macro1 program='" + program + "' macroVal='" + macroVal + "'";
}
out += "\">";
out += text;
out += "</span>";
console.log("out " + out);
$("p").on("click" , "span.macro1" , function(e)
{
BqlUtil.myFunction(program, macroVal);
});
}else{
var out = text;
}
return out;
};
console.log of out give me this
<span class="macro consolas-text macro1 program='test1' macroVal='test2'">{TEST}</span>
I have tried both this.program and program but it doesn't work.
Obtain values of span element attributes, since you include them in html:
$("p").on("click" , "span.macro" , function(e)
{
BqlUtil.myFunction(this.getAttribute("program"),
this.getAttribute("macroVal"));
});
There are, however, several things wrong in your code.
you specify class attribute twice in html assigned to out,
single quotes you use are not correct (use ', not ’),
quotes of attribute values are messed up: consistently use either single or double quotes for attribute values
var out = "<span class='";
...
out += "' class='macro' program='" + program + "' macroVal='" + macroVal + ;
...
out += "'>";
depending on how many times you plan to call onClickTest, you may end up with multiple click event handlers for p span.macro.

Call a javascript function from anchor tag inside td inside javascript code

Only Basic javascript knowledge is required.If anyone knows please help me.
I don't know how to do it but i have tried it in many ways but still not able to pass the value.
Simply, i have a for loop and i have a td inside it. I want to call a javascript function from this td click but problem is i am unable to pass any parameter to this function.
the code is here :
function GetContractList(abc) {
var data = abc
for (var it in data) {
tab += "<tr>";
tab += "<td>" + data[it].ContractCode + "</td>";
if (data[it].ContractCode != "") {
var Contract = data[it].ContractCode;
tab += "<td><a onclick='Delete_User(Contract);'>View</td>";
// tab += "<td><a data=" + data[it].ContractCode + " href='javascript:Delete_User(this.data);'>View</td>";
}
else {
tab += "<td></td>";
}
As u can see, i have tried to pass parameter to Delete_User function but the syntax is somewhere broken.
tab += "<td><a onclick='Delete_User(Contract);'>View</td>";
this line gives error-- Contract is not defined.
"<td><a data=" + data[it].ContractCode + " href='javascript:Delete_User(this.data);'>View</td>".
This line also doesnot passes any value to the function.
Please someone help me out.
try:
var cont = data[it].ContractCode.replace(/"/g, '\\"');
tab += '<td><a onclick="Delete_User(\''+cont+'\');">View</td>";
first line encodes any double quotes
the second line inserts the contract as a parameter and adds single quotes around it
You need to escape the quote for the parameter of the function.
tab += '<td>View</td>';
// ^^ ^^
function Delete_User(id) {
console.log('Delete_User', id);
}
var cc = '4711abc',
tab = 'View';
document.write(tab);

How to Prevent TD from ending up on a new line?

I am dynamically creating a table through Javascript and I DO want the table to continue off the right side of the page. Doing this manually lets the table continue off, but once I feed this into a for loop the <td>s wrap into a second line in the rendered HTML, creating two or more table rows when they reach the end of the page.
<div id="panelindex" style="overflow:scroll;text-align:center;">
<table border="0">
<tr></tr>
</table>
</div>
This is inside a table of its own (no style formatting). Then the Javascript:
var q = Math.floor((1/numpanels)*500);
if(q>50) q=50;
panelindex.innerHTML = "<table border='0'><tr>"
for(i=0; i<numpanels; i=i+1)
{
panelindex.innerHTML = panelindex.innerHTML + "<td><div id='panel" + i + "' onclick='jumppage(" + i + ")' style='float:left;text-align:center;margin:8px;border-width:3;border-color:white;border-style:none;'><a href='#" + i + "'><img src='thumbnails.php?image=blowem" + zeroFill(i,2) + ".gif&GIF&tw=128&th=128&quality=" + q + "'>\n" +
"<br />" + i + "</a></div></td>\n";
}
panelindex.innerHTML = panelindex.innerHTML + "</tr></table>"
You may notice that there is a <div> in the <td> and that is so I can apply a border marking the panel. Without the <div> it seems I cannot do that, and there are some other undesired effects. Any ideas what I can do so that all the <td>s end up on one line rather than split to a new line?
Example of what I want: http://edwardleuf.org/comics/jwb/009-conmet
What is happening: https://jsfiddle.net/w4uh0a3j/7/
Click the Show link.
innerHTML does not hold the string value you assign to it.
It parses the value as HTML, creates a DOM from it, inserts it into the document and then, when you read it back, it converts that DOM back into HTML.
This means that the string you assign is subject to error recovery and normalisation. In particular, the end tags you omitted are fixed.
panelindex.innerHTML = "<table border='0'><tr>"
console.log(panelindex.innerHTML);
<div id="panelindex" style="overflow:scroll;text-align:center;">
<table border="0"><tr>
</tr></table>
</div>
So when you start appending more data to it:
panelindex.innerHTML = panelindex.innerHTML + "<td>etc etc
You end up with:
<table border="0"><tbody><tr></tr></tbody></table><td>etc etc
Store your data in a regular variable. Only assign it to .innerHTML once you have the complete HTML finished.
A better approach then that would be to forget about trying to build HTML by mashing strings together (which is error prone, especially once you start dealing with characters that need escaping in HTML) and use DOM (createElement, appendChild, etc) instead.
OK,here is fixed html and js code. It seems like innerHTML fixes missing closing when updating html before all the code is building the rest of innerHTML. This code works :
<div id="panelindex" style="overflow:scroll;text-align:center;">
</div>
and js code :
var numpanels = 100;
var q = Math.floor((1/numpanels)*500);
if(q>50) q=50;
panelindex.innerHTML = "<table border='0'><tr>";
var html = "<table border='0'><tr>";
for(i=0; i<numpanels; i=i+1) {
html += "<td><div id='panel" + i + "' onclick='jumppage(" + i + ")' style='float:left;text-align:center;margin:8px;border-width:3;border-color:white;border-style:none;'><a href='#" + i + "'><img src='thumbnails.php?image=blowem" + ".gif&GIF&tw=128&th=128&quality=" + q + "'>\n" +
"<br />" + i + "</a></div></td>";
}
html += "</tr></table>";
document.getElementById("panelindex").innerHTML = html;

JavaScript: variable name unresolved

I wrote the following JS code:
function downloadFile(dataItem) {
....
}
....
for (var r = 0; r < dataItems.length ; r++) {
table += '<tr>';
var listOfAttributes = ['CarModel', 'BusMapping', 'Date_', 'Location_', 'Comments', 'AttackTraffic', 'IsTagged']
**table +='<td> <a onclick="downloadFile(dataItems[r])" href="#">' + dataItems[r]['FileName']['S'] +'</a></td>';**
for (var c = 0; c < Object.keys(dataItems[0]).length-1 ; c++) {
table +='<td>' + dataItems[r][listOfAttributes[c]]["S"] +'</td>';
}
table+= '</tr>'
}
I get an error for the line:
table +='<td> <a onclick="downloadFile(dataItems[r])" href="#">' + dataItems[r]['FileName']['S'] +'</a></td>';
It seems that JS can't resolve the variable 'dataItems' inside the -tag:
<a onclick="downloadFile(dataItems[r])" href="#">.
However, later in the same line, JS resolves successfully the same name for the part:
+ dataItems[r]['FileName']['S'] +
What do you think can be the problem? How can I make dataItems be resolved inside the -tag ?
Your variable is inside a string. Try changing the code to:
table +='<td> <a onclick="' + downloadFile(dataItems[r]) + '" href="#">' + dataItems[r]['FileName']['S'] +'</a></td>';**
As you're placing a string inside the element's attribute it is not recognized as a JavaScript code or a JavaScript function so place the JavaScript function itself.
So you can do, var anchor = '';
A sample example illustrating the problem, in this example if you write the function name as a string in the onclick property the function won't be called.
var container = document.getElementById('container');
var element = document.createElement('a');
element.href = '#';
element.text = 'Fire!';
element.onclick = fire; // this invokes the fire function
// element.onclick = 'fire'; // this won't invoke the fire function
container.appendChild(element);
function fire() {
console.log('fired');
}
<div id="container">
</div>
In this line
<a onclick="downloadFile(dataItems[r])" href="#">
unless dataItems is a global variable, it won't be available to the environment which will make this call downloadFile(dataItems[r]), since onclick event will be invoked in a global scope.
You need to bind the event less intrusively this way
//you need to update the selector as per your markup
document.querySelector ( "tr td a" ).addEventListener( "click", function(){
downloadFile(dataItems[r]);
})

Programmatically creating <DIV>s and problems arise

I am new to javascript and have written a piece of code (pasted below). I am trying to build a little game of Battleship. Think of that game with a grid where you place your ships and start clicking on opponents grid blindly if it will hit any of the opponents ships. Problem is I need to get a function called with the ID of the DIV to be passed as a parameter. When the DIV is programmatically created like below, what will work. This? : --///<.DIV id='whatever' onclick='javascript:function(this.ID)' /> .. I saw sth like that somewhere .. this inside html :S
the js code is: (there are two grids, represented by the parameter - who - ... size of grid is also parametric)
function createPlayGround(rows, who)
{
$('#container').hide();
var grid = document.getElementById("Grid" + who);
var sqnum = rows * rows;
var innercode = '<table cellpadding="0" cellspacing="0" border="0">';
innercode += '<tr>';
for (i=1;i<=sqnum;i++)
{
var rowno = Math.ceil(i / rows);
var colno = Math.ceil(i - ((rowno-1)*rows));
innercode += '<td><div id="' + who + '-' + i +'" class="GridBox'+ who +'" onmouseover="javascript:BlinkTarget(' + i + ',' + who +');" onclick="javascript:SelectTarget('+ i + ',' + who +');" >'+ letters[colno - 1] + rowno +'</div></td>';
if (i % rows == 0)
{
innercode += '</tr><tr>';
}
}
innercode += '</tr></table>';
grid.innerHTML = innercode;
$('#container').fadeIn('slow');
}
It sounds like what you really want is to get the div element that was just clicked on. If you just want to return the div that was clicked on, all you have to do is use "this":
<div id="whatever" onclick="function(this)"></div>
If you're actually more interested in getting the id of the div clicked on, you can do this:
<div id="whatever" onclick="function(this.id)"></div>
However, it sounds like you just want the id so that you can get the div using getElementById, and the first code snippet will help you skip that step.
Instead of creating the inner html from strings you can create it with jQuery and add event listeners like so:
$("<div></div>")
.click(function(e) {
selectTarget(i, who);
})
.appendTo(container);

Categories