So I got into this tricky situation. I have a variable which present table data:
row += '<td>' + c + '<button class="btn btn-success" id="' + callId + ' " onclick="handleCall()">Call</button>' + '<button class="btn btn-danger" id="' + hangupId + ' " onclick="handleHangUp()">Hangup</button>' + '</td>' ;
Latter on I will append that into my table. Now, when I click Call button, I want to get the button's Id. I have tried this way:
function handleClick() {
console.log(this);
}
but it refer to window object. Can anybody show me the way to achieve my goal? Thanks
Simply pass the elements ID as a parameter to keep it simple,
Change,
onclick="handleCall()"
to,
onclick="handleCall(this.id)"
this referring to the button in question the user is pressing.
then,
function handleClick(id) {
console.log(id);
}
Finally don't use inline event handlers as they are a pain to work with in the long run, make use of the addEventListener method.
row += '<td>' + c + '<button class="btn btn-success" id="' + callId + ' " onclick="handleCall(this)">Call</button>' + '<button class="btn btn-danger" id="' + hangupId + ' " onclick="handleHangUp()">Hangup</button>' + '</td>' ;
function handleClick(element) {
console.log(element);
//here you will have all element properties
}
There are two ways you can do this, you can do it via jQuery by using attr or if you are wanting to stay vanilla Javascript then you can use .id.
For jQuery please see code below:
console.log(jQuery('element').attr('id'));
For Javascript please see code below:
console.log(element.id);
Related
I would like to ask if it is possible to get innered div through javascript getElementById function.
this.treeContent = this.treeContent +
'<div id="tree' + htmlData.Id +
'" class="col-md-12">' + htmlData.Label + '</div>';
document.getElementById('tree' + htmlData.Id).innerHTML = '<button type="button" id="button' + htmlData.Id +
'" value="' + htmlData.Id + '">'
+ htmlData.Label + '</button>';
When i try code like this Cannot set property 'innerHTML' of null error rises. Thank you in advance for all replies.
You get Cannot set property 'innerHTML' of null error because you are trying to call document.getElementById and the element you want to get is not part of the DOM yet.
Try binding to tree content like this:
<div innerHtml="{{treeContent}}"></div>
By the way, you should try keeping as much HTML out of your JS files as possible. See https://angular.io/guide/displaying-data.
Json object pass as param in dynamicallay created element click event using javascript/angularjs
var _dataObj = "{"sor_SourcingAgentId":1,"sor_Name":"xx"}"
var _dynHtml= '<input type="button" ng-click="fnSelectcustomer(\'' + _dataObj + '\',\'' + data['sor_Name'].toString() + '\',\'' + data['sor_SourcingAgentId'].toString() + '\')" value="select"/>';
thanks in advance
If click event is not working in your code then use this
var _dynHtml= '<input type="button" ng-click="fnSelectcustomer(\'' + _dataObj + '\',\'' + data['sor_Name'].toString() + '\',\'' + data['sor_SourcingAgentId'].toString() + '\')" value="select"/>';
add below code in your controller
$compile(_dynHtml)($scope);
It will call your function. I guess this is what your looking for
A feature was developed in an application by clicking a hyperlink in a table, open a div below with a table, filtering contents, depending on the link.
The link was created dynamically in one jQuery function and had the following attributes:
$("#pending div#list").bind("data_loaded", function (event, records) {
var tableBody = $("tbody", $(this));
for (var index = 0; index < records.length; index++) {
var rowHtml = '<tr id="' + rowid + '"><input type="hidden" name="' + rowid + '" id="' + rowid + '" value="1"/>' +
'<td><a class="populate" id="' + rowid + '" onclick="javascript:clickHandler(' + rowid + ');">' + docid + '</a></td>' +
'</tr>';
tableBody.append($(rowHtml));
}
});
In Mozilla Firefox, it works perfectly fine. However in Chrome I cannot call the clickHandler function.
From the information I find on Google, say Inline JavaScript will not be executed.
You can check here: https://developer.chrome.com/extensions/contentSecurityPolicy
But now comes my difficulty.
I changed my hyperlink to:
'<td><a class="populate" id="' + rowid + '" onclick="clickHandler(' + rowid + ');">' + docid + '</a></td>' +
And I created this jQuery:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById([parameter]).addEventListener('click', function () { clickHandler([parameter]); },false);
});
Can anyone explain how I can pass the parameter rowid for jQuery?
Thanks.
Regards.
Your snippets imply you're using raw DOM manipulation in Javascript rather than JQuery (which is good! it's definitely faster) but since you mention JQuery, that's what I'll be suggesting.
Instead of your addEventListener call above, try
$('div#list').on('click', 'a.populate', function() {
clickHandler($(this).attr('id'));
});
And then remove the 'onclick' attribute in the declarations of the anchor tags too.
This will add an event listener to all anchor tages with a class of 'populate' which will call clickHandler passing a string parameter consisting of that anchor tag's 'id'.
I have a Html Table which displays data and is having delete and update functionality as below,
function DesignBTable(data) {
$("#ExpTableBody tr").remove();
var rowIndex = 0;
$.each(data, function (index, value) {
var fromDt = moment(value.from_date).format("MMM/YYYY");
var toDt = moment(value.to_date).format("MMM/YYYY");
$("#ExpTableBody").append("<tr>" +
"<td>" + value.org_name + "</td>" +
"<td>" + fromDt + "</td>" +
"<td>" + toDt + "</td>" +
"<td>" + value.designation + "</td>" +
"<td>" + value.location + "</td>" +
"<td>" + value.is_relevant + "</td>" +
"<td>" + '<input type="button" value = "X" class="btn btn-danger btn-sm" onClick="Javacsript:deleteRow(\'' + value.exp_id + '\',\'' + value.from_date + '\')">' + ' ' +
'<input type="button" value = "E" class="btn btn-info btn-sm" onClick="Javacsript:editRow(\'' + value + '\')">' + "</td>" +
"</tr>");
//alert(moment(value.from_date).format("MM/YYYY"));
rowIndex++;
});
};
The value object contains various fields.
On the Click event of the delete button I send value.exp_id and value.from_date as parameter to deleteRow function.
I want to add Edit functionality where if I click on the edit button it should send the value as object so that I can access all the fields in it.
When I try to send value as parameter to the JS function it errors out as undefined.
To create a string for code that uses the object, you would need to create a string representation of the object:
... onClick="editRow(' + JSON.stringify(value) + ')" ...
(Note: The JSON object is not supported in some older browsers.)
If you create elements directly instead of creating a string that you create elements from, you can bind the event directly and use the object without creating a string representation of it:
$("#ExpTableBody").append(
$("<tr>").append([
$("<td>").text(value.org_name),
$("<td>").text(fromDt),
$("<td>").text(toDt),
$("<td>").text(value.designation),
$("<td>").text(value.location),
$("<td>").text(value.is_relevant),
$("<td>").append([
$("<input>", { type: "button", value: "X", className: "btn btn-danger btn-sm" }).click(function(){
deleteRow(value.exp_id, value.from_date)
}),
$("<input>", { type: "button", value: "E", className: "btn btn-info btn-sm" }).click(function(){
editRow(value);
})
])
])
);
As a side effect, by using the text method to put the values in the cells, it's protected agains script injection. If you actually have HTML code that you want to put in a cell, you would use the html method instead. That naturally means that you should encode it properly when you create that HTML code to protect against script injection.
Side note: The javascript: pseudo protocol is only used when you put code in an URL, i.e. a href attribute. If you use it anywhere else it becomes a label instead. This is not harmful, but useless and confusing.
the problem of 'value' accessibility is it's defined only inside the function not outside.
I see you use JQuery, so you can use JQuery.data to make a link between an html object and a custom value. In your case you can add the value directly to the button at the end of the row.
I'm trying to create a dynamic table which will have rows added and removed throughout its use. I do not want to have to put id's on every container that I later want to reference.
For instance, I want to add a hidden input to the last cell of a dynamically added row. The row has an id, how can I use dojo.place() when I do not have an id on the last cell?
var pmrCount = dojo.query("#pmhTable >tbody >tr").length;
var rowID = 'pmr_' + pmrCount;
var newPmrRow =
'<tr id="' + rowID + '">' +
'<td>' + pmh + '</td>' +
'<td>' + String(pmr.severity).charAt(0) + '</td>' +
'<td>' + pmr.customerName + '</td>' +
'<td>' + pmr.deviceType + '</td>' +
'<td>' + pmr.deviceModel + '</td>' +
'<td>' + pmr.deviceSerial + '</td>' +
'<td align="center"><a class="cancel-link"></a></td>' +
'</tr>';
//dojo.place(newPmrRow, dojo.query("#pmhTable >tbody"));
var newPmrHiddenInput =
'<input type="hidden" name="pmrs" value="'+ JSON.stringify(pmr)+ '">';
//dojo.query("#" + rowID + " td:last").place(newPmrHiddenInput);
The two commented lines of code are the ones that I am trying to replace with functional code. These do not work, they don't surface any warnings in the error console like other syntax errors. Not sure where to go from here.
I know that dojo.query() returns a NodeList and place() is expecting an DOM node or an id. What's the correct way to do this?
You want to look at the dojo/NodeList-dom extension to Nodelist. It allows you to place each element in a NodeList into an element based on query selector . In AMD Style it looks like:
require(['dojo/dom-construct', 'dojo/NodeList', 'dojo/NodeList-dom', 'dojo/domReady!'], function (domConstruct, NodeList) {
var nodes = new NodeList([domConstruct.toDom('<div>someContent</div>')]);
nodes.place('#x');
});
Looking at the docs I was kind of surprised there wasn't an easier way to do this, so maybe there is a better way than this.
Well, I found two lines of code that seem to work, but I don't know if referencing NodeLists in an Array style is technically correct for this. This is what I did.
dojo.place(newPmrRow, dojo.query("#pmhTable >tbody")[0]);
dojo.place(newPmrHiddenInput, dojo.query("#" + rowID + "> td:last-child")[0]);