Assign click to dynamically created data from database - javascript

I have created javascript in which data is fetched for dropped element and are created. The data is fetched from database using json encoding. I have assigned id to the elements but the click event for every element is not working. only the last elements id is obtained and clicked is performed on that id.
JS :
$(document).ready(function () {
var i,j=0;
var x1,x2,y1,y2;
var sf=pf;
sf=Math.round(sf);
var tmp;
var y=null;
var idiv=[];
var fty=ft;
var fd=fid;
var fetch=data;
var x = null;
var count=fetch['count'];
var i=count+1;
//document.write(count);
var rai=[];
//rai[0]='hello';
//document.write(rai[0]);
var ww=[];
var hh=[];
var xx=[];
var yy=[];
var room=[];
var roomt=[];
for(j=0;j<=count;j++)
{
rai[j]=fetch['room_id'+j];
//document.write(rai[j]);
ww[j]=fetch['width'+j];
//document.write(ww[j]);
hh[j]=fetch['height'+j];
xx[j]=fetch['x'+j];
yy[j]=fetch['y'+j];
room[j]=fetch['room'+j];
roomt[j]=fetch['roomt'+j];
//document.write(room[j]);
// alert("data"+rai+" "+ww+" "+hh+" "+xx+" "+yy);
idiv[j]=document.createElement('img')
$('#droppable').append(idiv[j]);
idiv[j].style.position="absolute";
idiv[j].style.left=(xx[j]*sf)+'px';
idiv[j].style.top=(yy[j]*sf)+'px';
idiv[j].style.width=(ww[j]*sf)+'px';
idiv[j].style.height=(hh[j]*sf)+'px';
idiv[j].style.border=1+'px';
idiv[j].id=room[j];
//y=idiv[j].attr('idd',rai[j]);
if(roomt[j]=='garden')
{
idiv[j].src="images/download.jpg";
}
else
{
idiv[j].src="images/ac.png"
}
$(idiv[j]).draggable();
//alert(y);
//y=idiv[j].id;
// alert(y);
//document.write("data"+rai[j]+" "+(ww[j]*sf)+" "+(hh[j]*sf)+" "+(xx[j]*sf)+" "+(yy[j]*sf) + room[j]);
}
//$(this).bind("click",'idiv',function(){
// alert("hello"+idiv.id);
//window.location.href="tables.php?room_id="+y;
// });
});
can anyone give idea how to bind click on each fetched element.

Ty this : add class to the element created and write a click event handler for all element having that class. See below
Add below html in Loop where you are creating idiv[j] -
idiv[j].className = "clickable";
Now write a click event handler using .on()
$(document).ready(function () {
...... your code start here
......
//loop
for(j=0;j<=count;j++)
{
...
...
}
//loop ends
... more code
....your code end here
$(document).on("click",".clickable", function(){
alert(this.id);
});
});
NOTE: Don't use bind because it is deprecated now after jQuery version 1.5

Related

Bootastrap 3.3 tooltip in list

I have a list of elements that i want to dynamically change its data-original-title. What i did was have a async function that returns that content and then displays using a tooltipp.
This is the code:
function onElementOver(el) {
var pos = el.getAttribute('data-pos');
let contentTmp = arr[pos].content;
if (!contentTmp) {
let lat = arr[pos].lat;
let lng = arr[pos].lng;
getContent(lat, lng).then(function (ctn) {
contentTmp = ctn;
el.setAttribute('data-original-title', contentTmp);
$('[data-toggle="tooltip"]').tooltip();
arr[pos].content = ctn;
});
} else {
el.setAttribute('data-original-title', contentTmp);
$('[data-toggle="tooltip"]').tooltip();
}
}
I understand how the following line works, it gets all elements of the DOM wiht the data-toggle attribute, and displays it.
$('[data-toggle="tooltip"]').tooltip();
What I need is to only display the data-toggle in the element el argument of the onElementOver function.
How can I get it to only show that specific tooltip?
I haven't tested it but i assume $(el).tooltip() will work. if el is already a jquery element then use el.tooltip()

How do I add a RadToolTip to a JQuery dynamically generated table cell text

How do I add a Radtooltip to a text that appears in a dynamically created table cell using JQuery. The Tooltip popup should show the data from the cell along with a hyperlink. This is for a table displaying issues and the tooltip is suppose to display a link taking use to a resolution page.
function GenerateProblemResoultionLinks() {
// Open up the landing page for addressing the problem.
function problemLink_Click() {
// Get the problem data from the row.
var $self = $telerik.$(this);
var oProblemData = JSON.parse(
$self.attr("data-Problem")
);
// Add the original message to the problem data.
oProblemData["problemText"] = $self
.text()
.trim();
// Convert the object back to JSON and encode it for transport.
var strProblemDataArgument = encodeURIComponent(
JSON.stringify(oProblemData) );
var strURL =
"problemresolutionpage.aspx?problemData=" +
strProblemDataArgument;
window.open(strURL, "_blank");
}
// Set up the delegated event handler.
$telerik
.$(".PROBLEMDETAILS> tbody")
.on("click", ".problemLink", problemLink_Click);
}
I resolved my problem by modifying my code as follows:
function GenerateProblemResoultionLinks() {
function problemLink_Click() {
// Get the problem data from the row.
var $self = $telerik.$(this);
var oProblemData = JSON.parse(
$self.attr("data-integrationProblem")
);
// Add the original message to the problem data.
oProblemData["problemText"] = $self
.text()
.trim();
if (oProblemData){
// Generate problem soltuion tooltip for each problem type. Needs to stay within the scope of the onclick.
switch(oProblemData.type){
case "ProblemType1":
var IDForSolution1=oProblemData.data["layoutIDT"];
var IDForSolution2 = oProblemData.data["keywordTableIDT"];
var Soltuion1Link="UpdateItem";
var Solution2Link="Add New Record";
var toolTipTMsg ="A new record may be added to the record table <br/> OR<br/> item can be updated in the item table."
var radToolTip = $find("<%= RadToolTip1.ClientID %>");
radToolTip.set_targetControl(this);
radToolTip.set_content("<p>" +toolTipTMsg +"</p>-------------------</br>" + Soltuion1Link +"<br/>"+ Soltuion2Link);
radToolTip.show();
break;
default:
break;
}
}
}
// Set up the delegated event handler.
$telerik
.$(".IMPORTEXPORTDETAILS > tbody")
.on("click", ".problemLink", problemLink_Click);
}
and I added the following as well:
<telerik:RadToolTip RenderMode="Lightweight" ID="RadToolTip1" runat="server" Title="Problem Solution(s)" IsClientID="true" Callout="false" RelativeTo="Element" Position="MiddleRight" ShowEvent="FromCode" Height="220" Width="300" HideEvent="LeaveToolTip">
</telerik:RadToolTip>

Troubleshooting Conditional Form

I'm new to Javascript and trying to build a conditional form using bootstrap and JQuery. I would really appreciate the help as I've been working most of the day on this to no avail.
I'm trying to show the div with id physician (and subsequent field) when the select field with the name AppointmentType has a value of Orthopedic or Rheumatology. Here is the link to the live form.
Here is my javascript:
$( document ).ready(function() { //wait until body loads
//Inputs that determine what fields to show
var appttype = $('#secureform input:select[name=AppointmentType]');
var physician = document.getElementById("physician");
appttype.change(function(){ //when the Appointment Type changes
var value=this.value;
physician.addClass('hidden'); //hide everything and reveal as needed
if (value === 'Orthopedic' || value === 'Rheumatology'){
physician.removeClass('hidden'); //show doctors
}
else {}
});
});
These lines are going to cause errors (which you should see in your devtools console):
var appttype = $('#secureform input:select[name=AppointmentType]'); // `input:select` is not a valid selector and causes the rest of the script to fail
physician.addClass('hidden'); // `addClass` is a jQuery method, so this should be `$(physician).addClass('hidden')`
physician.removeClass('hidden');// `removeClass` is a jQuery method, so this should be `$(physician).removeClass('hidden')`
Correct those lines and it should work.
If it helps, I would write it like this:
$( document ).ready(function () {
//Inputs that determine what fields to show
var apptType = $('#secureform select[name="AppointmentType"]'); // dropped the `input:` part
var physician = document.getElementById('physician');
physician.classList.add('hidden'); //hide this initially, outside the change handler
apptType.change(function () { // when the Appointment Type changes
var value = $(this).val().toLowerCase(); // leave case-sensitivity out of it.
var showables = [ // using an array as I prefer using a simple `indexOf` for multiple comparisons
'orthopedic',
'rheumatology',
];
var isShowable = showables.indexOf(value) > -1;
physician.classList.toggle('hidden', !isShowable);
// or, the jQuery equivalent:
// $(physician).toggleClass('hidden', !isShowable);
});
});
Your selector is incorrect:
var appttype = $('#secureform input:select[name=AppointmentType]');
// this should be
var appttype = $('#secureform select[name=AppointmentType]');
Furthermore you are mixing jquery with vanilla JS. Your are using vanilla js here
var physician = document.getElementById("physician");
Physician is now a dom object and not a jquery object. You should use this instead:
var physician = $("#physician");
Additionally you should replace
var value=this.value;
with this
var value= $(this).val();

Adding a custom attribute in ASP.NET. accessing it in JQuery

I have a table that is created in ASP.NET C# code behind. The table has several levels of groupings, and when I create the rows for the outer most grouping, I add an custom attribute as follows:
foreach (Table2Row row in Table2Data)
{
// skipping a bunch of irrelevent stuff
...
tr_group.Attributes.Add("RowsToToggle", String.Format(".InnerRowGroupId_{0}", row.GroupHeaderId));
...
}
The attribute is the CSS class name of the inner level rows that I would like to toggle. When the user clicks on the outer level row, I would like to call JQuery Toggle function for all inner level rows that match the custom attribute.
To achieve that effect, I have attached an onclick event to the header rows with the following script in the aspx file:
var tableId = '<%= Table2MainTable.ClientID %>';
$(document).ready(function () {
var table = document.getElementById(tableId);
var groupRows = table.getElementsByClassName("Table2GroupHeaderRow");
for (i = 0; i < groupRows.length; i++) {
table.groupRows[i].onclick = function () { ToggleOnRowClick(table.rows[i]); }
}
});
function ToggleOnRowClick(row) {
var r = $('#' + row.id);
var innerRows = r.attr('RowsToToggle');
$(innerRows ).toggle();
}
So, clicking anywhere on the header row should call the function ToggleOnRowClick, which should then toggle the set of rows below it via the custom attribute RowsToToggle.
When I set a (FireBug) break point in the ToggleOnRow function, the variable r appears to be pointing to the correct object. However, innerRows is not getting set but instead remains null. So am I setting the custom attribute incorrectly in ASP.NET or reading in incorrectly in JQuery?
You did not post the code to generate inner level rows, I am assuming you sat proper classes to them.
There are few issues with the jquery you posted. This line wouldn't work:
table.groupRows[i].onclick = function () { ToggleOnRowClick(table.rows[i]); }
You don't have any groupRows property defined for table object.
We don't care about table row anymore, we care about groupRows[i] and want to pass it to ToggleOnRowClick function.
This line in next function is also wrong:var r = $('#' + row.id);
Solution: Change your script to this:
var tableId = '<%= Table2MainTable.ClientID %>';
$(document).ready(function () {
var table = document.getElementById(tableId);
var groupRows = table.getElementsByClassName("Table2GroupHeaderRow");
for (i = 0; i < groupRows.length; i++) {
groupRows[i].onclick = function () { ToggleOnRowClick(this); }
}
});
function ToggleOnRowClick(row) {
//var r = $('#' + row.id);
var innerRows = $(row).attr('RowsToToggle');
$("." + innerRows).toggle();
}
I have tested the code with dummy data. So if you have any issue, PM me.
This line is your culprit:
table.groupRows[i].onclick = function () { ToggleOnRowClick(table.rows[i])
By the time the event handler runs, table.rows might still exist, but i will be set to groupRows.length+1, which is out of bounds for the array. The handler will get called with an argument of undefined.
Remember, Javascript is an interpreted language! The expression "table.rows[i]" will get interpeted when the handler runs. It will use the last value of i (which will still be set to the value that caused your for loop to end, groupRows.length+1).
Just use
table.groupRows[i].onclick = function () { ToggleOnRowClick(this) }
So, First you shouldn't use custom attributes... they are a sin!
Please use data attributes instead, so that is what I'm going to use in the code, should be an easy fix regardless.
If this doesn't work then I'd be very very interested in seeing a dumbed down HTML snippet of the actual output.
$(document).ready(function () {
$('#MYTABLE').on('click', '.Table2GroupHeader', function() {
var attr_if_you_insist_on_sinning = $(this).attr("RowsToToggle");
var data_if_you_like_not_sinning = $(this).data("RowsToToggle");
//if the row is like <tr data-RowsToToggle=".BLAH" or th etc
//asumming you set the attribute to .BLAH then:
var rows_to_toggle = $(data_if_you_like_not_sinning);
rows_to_toggle.toggle();
//assuming you set it to BLAH then:
var rows_to_toggle = $("."+ data_if_you_like_not_sinning);
rows_to_toggle.toggle();
});
});
$(document).ready(function () {
$('#<%= Table2MainTable.ClientID %> .Table2GroupHeader').each(function(){
$(this).click(function(){
$(this).toggle();
});
});
});

obj is null, javascript

function init()
{
alert("init()");
/**
* Adds an event listener to onclick event on the start button.
*/
xbEvent.addEventListener(document.getElementById("viewInvitation"), "click", function()
{
new Ajax().sendRequest("31260xml/invitations.xml", null, new PageMaster());
xbEvent.addEventListener(document.getElementById("declinebutton"), "click", function ()
{
declineInvitation();
});
});
ok so what I have here is a event listerner function, the case is when viewInvitation is clicked , the program will fetch my xml file and run page master function where I created my decline button with id="declinebutton", however this does not work, the error message that i get is obj=null or the program could not find id = declinebutton, why is it so? I have created it when I called page master using dom. any help will be appreciated.
function PageMaster()
{
this.contentDiv = document.getElementById("content");
}
/**
* Builds the main part of the web page based on the given XML document object
*
* #param {Object} xmlDoc the given XML document object
*/
var subjectList;
var i;
PageMaster.prototype.doIt = function(xmlDoc)
{
alert("PageMaster()");
alert("Clear page...");
this.contentDiv.innerHTML = "";
if (null != xmlDoc)
{
alert("Build page...");
//create div Post
var divPost = document.createElement("div");
divPost.className = "post";
//create h1 element
var h1Element = document.createElement("h1");
var headingText = document.createTextNode("Invitations");
h1Element.appendChild(headingText);
//insert h1 element into div post
divPost.appendChild(h1Element);
subjectList = xmlDoc.getElementsByTagName("subject");
var groupList = xmlDoc.getElementsByTagName("group");
for (i = 0; i < subjectList.length; i++) //for each subject
{
var divEntry = document.createElement("div");
divEntry.className = "entry";
var subjectNum = subjectList[i].attributes[0].nodeValue;
var subjectName = subjectList[i].attributes[1].nodeValue;
var groupId = groupList[i].attributes[0].nodeValue;
var groupName = groupList[i].attributes[1].nodeValue;
var ownerId = groupList[i].attributes[2].nodeValue;
//set up the invitation table attributes
var table=document.createElement("table");
table.width = 411;
table.border = 3;
table.borderColor = "#990000"
var input=document.createElement("p");
var inputText=document.createTextNode("You are invited to join " + groupName + "(groupId : " + groupId +")");
input.className="style11";
var blank=document.createElement("nbps");
input.appendChild(inputText);
var acceptButton=document.createElement("input");
acceptButton.type="button";
acceptButton.id="acceptbutton";
acceptButton.value="accept";
var declineButton=document.createElement("input");
declineButton.type="button";
declineButton.id="declinebutton";
declineButton.value="decline";
table.appendChild(input);
table.appendChild(acceptButton);
table.appendChild(declineButton);
divEntry.appendChild(table);
var blankSpace = document.createElement("p");
divEntry.appendChild(blankSpace);
divPost.appendChild(divEntry);
}
//insert div post into div content
this.contentDiv.appendChild(divPost);
}
};
/**function getValueOf()
{
return i;
}**/
function declineInvitation()
{
alert("decline");
}
function acceptInvitation()
{
alert("hello");
/**var pos=getValueOf();
alert(subjectList[pos].attributes[0].nodeValue);**/
}
That's my page master function, and I definitely have created the button. but it does not work.
Try calling your function like this:
window.onload=init;
The javascript runs as the page loads. At that point, the element does not yet exist in the DOM tree. You'll need to delay the script until the page has loaded.
The example you gave doesn't create the "Decline" button, as your question suggests it should. If it should, you might want to look at that.
Of course, if the button already exists, please disregard this answer.
You have a listener inside a listener. Is that right?
What about this?:
function init(){
alert("init()");
/** * Adds an event listener to onclick event on the start button. */
xbEvent.addEventListener(document.getElementById("viewInvitation"), "click", function()
{
new Ajax().sendRequest("31260xml/invitations.xml", null, new PageMaster());
}
xbEvent.addEventListener(document.getElementById("declinebutton"), "click", function ()
{
declineInvitation();
});
As far as I understand, you create button with id="declinebutton" for each entry from xml, is that right?
If yes, I'd suggest you to generate different id's for each button (for example, append line index to 'declinebutton', so you have buttons 'declinebutton0', 'declinebutton1' an so on), and assign event listener to buttons separately in the loop.

Categories