Actually in my website i'm building a timeline from AJAX and i was trying to set the onclick on each table row.
I was using class selector but the effect was nothing.
I actually read in another stackoverflow post that i had to set onclick on the closest static item but nothing.
So i've tryed
$(".timeline").on("click","table-row",function () { alert("we") ;});
and
$(".table-row").click(function () { alert("we"); });
Actually AJAX code where i create the timeline is the following
function createTavoli(salaSelect) {
$.ajax({
type: "POST",
url: "Default.aspx/getTavoli",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
data = r.d;
data = $.parseJSON(data);
var count = 0;
var time = [];
$.each(data, function (i, item) {
var tabs = [];
var numtav = item.NUM_TAV;
var desctav = item.DESC_T;
var coperti = item.COPERTI;
var sala = item.SALA;
if (sala == salaSelect) {
tabs.push('<tr id="' + numtav + '" data-salatav="' + sala + '" class="table-row">');
if (desctav != "") {
tabs.push('<th scope="row" class="noselect row-head text-left">' + desctav + '<span class="badge badge-dark ml-1">' + coperti + '</span></th>');
} else {
tabs.push('<th scope="row" class="noselect row-head text-left">' + "T. " + numtav + '<span class="badge badge-dark ml-1">' + coperti + '</span></th>');
}
for (var i = 0; i <= 95 - Range; i++) {
tabs.push('<td style="padding: 0px; position: relative; z-index: 1;"></td>');
}
tabs.push('</tr>');
count++;
$('#timeline').append(tabs.join(""));
}
});
time.push('<th scope="col" style="padding: 0px; border: 0; width: 80px;" class="row-head"></th>');
for (var i = PartenzaOra; i <= 23; i++) {
time.push('<th style="padding: 0px; border: 0; z-index: 3;" scope="colgroup" colspan="4"><p class="h noselect">' + ('0' + i).slice(-2) + '</p></th>');
}
$('#timehead').append(time.join(""));
$('#counttav').text(count);
getTavoli(new Date());
},
error: function (xhr, status, errorThrow) {
alert(xhr.status + " " + xhr.responseText);
}
});
}
So which could be the best method to set onclick on the table-row class?
Here is JSFiddle of how's build the timeline
You should set click event after rows pushed to table. So put your $(".table-row").click(function () { alert("we"); }); code to end of success function.
Did you tried
$(document).on("click", ".timeline .table-row" , function() {
alert("we");
});
you can try this
$('body').on("click", ".table-row" , function() {
alert("we");
});
Related
I'm using the dragable and droppable function in javascript to move cells in a GridView.
Everything works, the only thing I don't like, when I move a cell it shifts everything as if moving the td.
The programming language used is VB.NET, while the drag-and-drop part I used Javascript.
Do you think it is also possible to insert the switch function between two names in two different cells?
Any advice?
Thank you very much!!
Gif of what's going on
var colIndex, rowIndex;
$('[id^="GridView"] tr td').draggable({
revert: "invalid",
zIndex: 100,
start: function (event, ui) {
var foo = $(ui.helper).parent();
colIndex = foo.index();
rowIndex = foo.parent().index();
$(ui.helper).css({
padding: "2.5px 5px",
border: "1px solid #ddd",
background: "#f2f2f2"
});
}
});
$('#GridView2 tr td').droppable({
accept: "#GridView1 tr td, #GridView2 tr td",
activeClass: "ui-state-highlight",
drop: function (ev, ui) {
var foo2 = $(ui.helper).parent();
colIndex2 = foo2.index();
rowIndex2 = foo2.parent().index();
var foo = $(ev.target);
var spanCount = foo.find('span').length;
var myColInd = foo.index();
var myRowInd = foo.parent().index();
var text_dest = foo.text();
if (text_dest == String.fromCharCode(160) || text_dest == '') {
var x = document.getElementById($(this).closest('table').attr('id')).rows
var y = x[myRowInd].cells
y[myColInd].innerHTML = ""
$(ui.draggable).detach().css({
top: 'auto',
left: 'auto',
background: '#f3f3f3'
}).appendTo(this);
var arr = [];
$("#" + $(this).closest('table').attr('id') + " tr").each(function () {
arr.push($(this).find("th").eq(myColInd).text());
});
var arr2 = [];
$("#" + $(this).closest('table').attr('id') + " tr").each(function () {
arr2.push($(this).find("td").eq(myColInd).text());
});
let prefix = $('#DropDownList1').val() + ',Lu,' + myRowInd + ',' + arr[0] + ',' + arr2[myRowInd] + ',' + $('#Label1').text() + ',' + $('#Label2').text();
$.ajax({
type: "POST",
url: "index.aspx/InsRec",
data: "{ 'prefix': '" + prefix + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: code1
});
}
else {
$(ui.draggable).draggable('option', 'revert', true);
return false;
};
}
});
Im not sure what is happening here, but I can not update this DIV per every row using this code. This code loads a initial user list, and loads the rest (after first 3) to a DIV dropdown triggered by click event.
<? foreach ($res as $row) { ?>
<script>
function fetchIndexUsers() {
$(function () {});
$.ajax({
url: '/ajax/ajax_live_index_users.php',
method: 'GET',
cache: false,
dataType: 'JSON',
data: {
item_id: <?=intval($row["item_id"])?>
},
success: function (data) {
var html_to_append = '';
array = [];
results = [];
$.each(data, function (i, item) {
results[i] = data[i];
array[0] = item.total;
array[1] = item.calc;
let icon = item.user.match(/(^|\W)yes($|\W)/i) ? 'arrow_upward' : 'arrow_downward';
html_to_append += '<div style="display:inline;float:left"><span class="material-icons" style="vertical-align:top;width:16px;padding-right:30px;color:#c0c0c0">' + icon + '</span></div><div style="display:inline;float:left;padding-bottom:1px"><a class="tooltip-newusers" title="' + item.username + '" href="/user/?id=' + item.user_id + '"><img style="box-shadow:2px 2px 10px #D3D3D3;height:35px;width:35px;border-radius:50%;margin-bottom:6px;margin-right:-20px;margin-top:-5px;vertical-align:middle;position:relative;z-index:10005;border:2px solid #FFF" src="/' + item.avatar + '" /></a></div><div style="clear:both"></div>';
return i <= 3;
});
if (array[0] >= 3) {
$("#live-peers-more-<?=intval($row["item_id"])?>").html('<div id="slidedown-<?=intval($row["item_id"])?>" style="user-select:none;margin-top:-14px;position:absolute;right:-20px;font-size:13px;background:purple;padding:0 6px;text-align:center;border-radius:3px;color:#FFF;font-weight:500;text-decoration:none;text-shadow:0 1px 1px rgba(0,0,0,.3);box-shadow:2px 2px 10px #D3D3D3"><a style="color:#fff;cursor:pointer">+ ' + (array.length - array[1]) + (array[1] >= 2 ? ' peers' : ' peer') + '</a></div>')
if (array[1] === 0) {
$("#live-users-more-<?=intval($row["item_id"])?>").hide();
}
}
$("#live-users-<?=intval($row["item_id"])?>").html(html_to_append);
$('.tooltip-newusers').tooltipster({
animation: 'grow',
delay: 200,
interactive: true,
theme: 'tooltipster-punk'
});
$("#live-peers-<?=intval($row["item_id"])?>").css('background', 'none');
$("#slidedown-<?=intval($row["item_id"])?>").html('<span><a style="color:#fff;cursor:pointer">+ ' + array[0] + (array[0] >= 2 ? ' peers' : ' peer') + '</a></span>');
}
});
$("#live-users-more-<?=intval($row["item_id"])?>").click(function () {
$("#slidedown-<?=intval($row["item_id"])?>").css('z-index', '9999999');
$.ajax({
url: '/ajax/ajax_live_index_users.php',
method: 'GET',
cache: false,
dataType: 'JSON',
data: {
item_id: <?=intval($row["item_id"])?>,
more: 1
},
success: function (data) {
var html_to_append = '';
$.each(results, function (i, item) {
html_to_append += '<div id="more_users" style="padding:6px;text-shadow:0 1px 1px rgba(0,0,0,.3)"><div id="peer-username">' + truncateString(item.username, 6) + '</div><a class="tooltip-newusers" title="' + item.username + '" href="/user/?id=' + item.user_id + '"><img style="height:35px;width:35px;border-radius:50%;border:2px solid #FFF" src="/' + item.avatar + '" /></a><div style="font-size:11px;font-weight:normal">' + formatBytesSpeed(item.totalspeed) + '</div></div>';
$("#slidedown-<?=intval($row["item_id"])?>").css('height', 'auto');
});
$("#slidedown-<?=intval($row["item_id"])?>").html(html_to_append);
$('.tooltip-newusers').tooltipster({
animation: 'grow',
delay: 200,
interactive: true,
theme: 'tooltipster-punk'
});
}
});
});
}
fetchIndexUsers();
setInterval(function () {
fetchIndexUsers()
}, 5000);
</script>
<div id="live-users-<?=intval($row["item_id"])?>" style="padding:10px;background:url(/images/loading-ellipsis.svg) no-repeat left">
<span style="padding-right:89px"></span>
</div>
<div id="live-users-more-<?=intval($row["item_id"])?>"></div>
<? } ?>
But any action coming back only updates the last row in from the array (PHP foreach array, with the JS emedded in the loop picking up on the ID from the iteration).
How come it only interacts with the last row? How can I update all rows since I am using a unique ID?
Thank you
You need to move the script out from the loop completely. Have ONE version of the script that delegates like this
$("#container").on("click", ".live-users-more",function () {
const item_id = $(this).prev().attr("id"); ....
and then change
<div id="live-users-more-<?=intval($row["item_id"])?>"></div>
to
<div class="live-users-more"></div>
where you have a
<div id="container"></div>
that wraps all the live user divs
I hope you are fine!
I'm new in coding so I'm facing of something without results.
I have this type of code here in JS.
key: 'generateChart2',
value: function generateChart2() {
var self = this;
var Jahr1 = [];
var years1 = "";
for (var i = 0; i < $('#mf123_select_jahr').val().length; i++) {
if (i > 0) years1 += ","
years1 += $('#mf123_select_jahr').val()[i];
}
var postedData1 = {};
postedData1.years1 = years1;
console.log(postedData1);
$.ajax({
url: "data/json.dashboard.php?call=chart2",
data: postedData1,
dataType: 'json',
type: 'POST',
success: function (dataGraph2) {
var trHTML='';
$.each(dataGraph2, function (key, value) {
for (var i in postedData1) {
Jahr1.push(postedData1[i].years1);
}
console.log(postedData1.years1);
trHTML +=
'<tr><td >' + value.Mandant +
'</td><td >' + thousandSepNeu(value.Jahr1, 2) + " €" +
'</td><td >' + value.Growth +
'</td></tr>';
});
$('#dataGraph2').append(trHTML);
}
});
}
The value.Mandant and the value.Growth are doing well. The problem that I have is that the for loop does not work. I need to thr postedData1 to choose whenever the user choose the year to show him the results.
The output of console.log(postedData1); is:
Am I making a mistake? I know that the problem is on the for loop.
Please any advice i would appreciate it.
:)
I have input which on change should send it is value to ajax and get response back. Ajax is working correct and enters to success,but does not working click function inside it if i do not do changes or click. If i click immediately after response it works, but if i do not do changes in 4-5 seconds it something like close the session. How can i avoid this timing?
here is my example of ajax
$('#unvan_search').on('keyup change', function() {
var unvan = $(this).val();
$.ajax({
type: "POST",
url: url,
data: {
'tpIdRegion': region_type_id_j + '_' + region_id_j,
'road': unvan,
'guid': my_key
},
beforeSend: function() {
console.log('before send');
},
success: function(e) {
console.log('suceess');
var output = [];
for (var i = 0; i < e.names.length; i++) {
output.push('<li class="get_street es-visible" idx="' + e.names[i].X + '" idy="' + e.names[i].Y + '" id="' + e.names[i].ID + '" value="' + e.names[i].ID + '" style="display: block;">' + e.names[i].Name + '</li>');
console.log('filled');
};
$('#unvan_select_div ul').html(output.join(''));
$("#unvan_select_div ul").on("click", '.get_street', function() {
//MY CODE HERE WHICH I CAN NOT USE AFTER 4-5 SECONDS
});
},
error: function(x, t, m) {
alert("error");
}
});
});
This binding here:
$("#unvan_select_div ul").on("click", '.get_street', function() { ... }
There’s no need to declare it in the success callback. This kind of delegate bindings is there for that purpose: being able to handle events on elements created at a later stage
It may work if you structure it like this.
var ret = false;
$.ajax({
type: "POST",
url: url,
data: {
'tpIdRegion': region_type_id_j + '_' + region_id_j,
'road': unvan,
'guid': my_key
},
beforeSend: function() {
console.log('before send');
},
success: function(e) {
ret = true;
console.log('suceess');
var output = [];
for (var i = 0; i < e.names.length; i++) {
output.push('<li class="get_street es-visible" idx="' + e.names[i].X + '" idy="' + e.names[i].Y + '" id="' + e.names[i].ID + '" value="' + e.names[i].ID + '" style="display: block;">' + e.names[i].Name + '</li>');
console.log('filled');
};
return;
},
error: function(x, t, m) {
alert("error");
}
});
});
if(ret) {
$('#unvan_select_div ul').html(output.join(''));
$("#unvan_select_div ul").on("click", '.get_street', function() {
//MY CODE HERE WHICH I CAN NOT USE AFTER 4-5 SECONDS
});
}
I am new to JQuery and doesn't know how to handle errors like uncaught TypeError: undefined is not a function. I don't know how to put the jQuery code below in order. Can someone please arrange it in order....
#model Mvc4_WebGrid_CRUD.Models.PagedCustomerModel
#{
ViewBag.Title = "WebGrid CRUD Operations";
WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize);
grid.Bind(Model.Customer,
autoSortAndPage: false,
rowCount: Model.TotalRows
);
}
<style type="text/css">
#grid {
clear: both;
width: 80%;
margin: 0px;
border: 1px solid #c7c5c7;
}
#grid thead, #grid tfoot td {
text-align: left;
font-weight: bold;
height: 35px;
color: #000;
background-color: #d2d0d2;
border-bottom: 1px solid #e2e2e2;
}
#grid td {
padding: 4px 6px 0px 4px;
vertical-align: top;
background-color: #f5f5f5;
border-bottom: 1px solid #e2e2e2;
}
input {
border: 1px solid #e2e2e2;
background: #fff;
color: #333;
font-size: 1.2em;
margin: 2px 0 2px 0px;
padding: 2px;
width: 170px;
}
</style>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//Here is where I get the error
$("#results").dialog({
autoOpen: false,
title: 'Title',
draggable: false,
width: 500,
height: 400,
model: true,
success: function () {
alert('working fine');
}
});
});
function openPopup() {
$("#results").dialog("open");
}
</script>
The below code works fine
<script type="text/javascript">
$(".add").live("click", function () {
var existrow = $('.save').length;
if (existrow == 0) {
var index = $("#grid tbody tr").length + 1;
var Name = "Name_" + index;
var Address = "Address_" + index;
var ContactNo = "ContactNo_" + index;
var Save = "Save_" + index;
var Cancel = "Cancel_" + index;
var tr = '<tr class="alternate-row"><td></td><td><span> <input id="' + Name + '" type="text" /></span></td>' +
'<td><span> <input id="' + Address + '" type="text" /></span></td>' +
'<td><span> <input id="' + ContactNo + '" type="text" /></span></td>' +
'<td> SaveCancel</td>' +
'</tr>';
$("#grid tbody").append(tr);
}
else {
alert('First Save your previous record !!');
}
});
$(".icancel").live("click", function () {
var flag = confirm('Are you sure to cancel');
if (flag) {
$(this).parents("tr").remove();
}
});
$(".save").live("click", function () {
var id = $("#grid tbody tr").length;
var Name = $("#Name_" + id).val();
var Address = $("#Address_" + id).val();
var ContactNo = $("#ContactNo_" + id).val();
if (id != "") {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("SaveRecord", "Home")',
data: { "name": Name, "address": Address, "contactno": ContactNo },
dataType: "json",
beforeSend: function () { },
success: function (data) {
if (data.result == true) {
$("#divmsg").html("Record has been saved successfully !!");
setTimeout(function () { window.location.replace("WebGridCRUD"); }, 2000);
}
else {
alert('There is some error');
}
}
});
}
});
$(".edit").live("click", function () {
var str = $(this).attr("id").split("_");
id = str[1];
var Name = "#Name_" + id;
var spanName = "#spanName_" + id;
var Address = "#Address_" + id;
var spanAddress = "#spanAddress_" + id;
var ContactNo = "#ContactNo_" + id;
var spanContactNo = "#spanContactNo_" + id;
$(Name).show();
$(spanName).hide();
$(Address).show();
$(spanAddress).hide();
$(ContactNo).show();
$(spanContactNo).hide();
$(this).hide();
$("#Update_" + id).show();
$("#Cancel_" + id).show();
});
$(".cancel").live("click", function () {
var str = $(this).attr("id").split("_");
id = str[1];
var Name = "#Name_" + id;
var spanName = "#spanName_" + id;
var Address = "#Address_" + id;
var spanAddress = "#spanAddress_" + id;
var ContactNo = "#ContactNo_" + id;
var spanContactNo = "#spanContactNo_" + id;
$(Name).hide();
$(spanName).show();
$(Address).hide();
$(spanAddress).show();
$(ContactNo).hide();
$(spanContactNo).show();
$(this).hide();
$("#Update_" + id).hide();
$("#Edit_" + id).show();
});
$(".update").live("click", function () {
var str = $(this).attr("id").split("_");
id = str[1];
var Name = $("#Name_" + id).val();
var spanName = $("#spanName_" + id).val();
var Address = $("#Address_" + id).val();
var spanAddress = $("#spanAddress_" + id).val();
var ContactNo = $("#ContactNo_" + id).val();
var spanContactNo = $("#spanContactNo_" + id).val();
if (id != "") {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("UpdateRecord", "Home")',
data: { "id": id, "name": Name, "address": Address, "contactno": ContactNo },
dataType: "json",
beforeSend: function () {//alert(id);
},
success: function (data) {
if (data.result == true) {
$("#Update_" + id).hide();
$("#Cancel_" + id).hide();
$("#Edit_" + id).show();
var Name = "#Name_" + id;
var spanName = "#spanName_" + id;
var Address = "#Address_" + id;
var spanAddress = "#spanAddress_" + id;
var ContactNo = "#ContactNo_" + id;
var spanContactNo = "#spanContactNo_" + id;
$(Name).hide();
$(spanName).show();
$(Address).hide();
$(spanAddress).show();
$(ContactNo).hide();
$(spanContactNo).show();
$(spanName).text($(Name).val());
$(spanAddress).text($(Address).val());
$(spanContactNo).text($(ContactNo).val());
}
else {
alert('There is some error');
}
}
});
}
});
$(".delete").live("click", function () {
var str = $(this).attr("id").split("_");
id = str[1];
var flag = confirm('Are you sure to delete ??');
if (id != "" && flag) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("DeleteRecord", "Home")',
data: { "id": id },
dataType: "json",
beforeSend: function () { },
success: function (data) {
if (data.result == true) {
$("#Update_" + id).parents("tr").remove();
}
else {
alert('There is some error');
}
}
});
}
});
</script>
<div id="divmsg" style="color: green; font-weight: bold"></div>
Add New
<br />
<br />
#grid.GetHtml(
htmlAttributes: new { id = "grid" },
fillEmptyRows: false,
mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
columns: new[] {
grid.Column("CustID",
header: "ID", canSort: false),
grid.Column(header: "Name",format: #<span> <span id="spanName_#item.CustID">#item.Name</span> #Html.TextBox("Name_"+(int)item.CustID,(string)item.Name,new{#style="display:none"})</span>),
grid.Column(header: "Address",format: #<span> <span id="spanAddress_#item.CustID">#item.Address</span> #Html.TextBox("Address_"+(int)item.CustID,(string)item.Address,new{#style="display:none"})</span>),
grid.Column(header: "Contact No",format: #<span> <span id="spanContactNo_#item.CustID">#item.ContactNo</span> #Html.TextBox("ContactNo_"+(int)item.CustID,(string)item.ContactNo,new{#style="display:none"})</span>),
grid.Column(header: "Action",format:#<text>
Edit
Update
Cancel
Delete
Details
#Ajax.ActionLink("Ajax Link","AjaxView",new{Id=#item.CustID},new AjaxOptions { HttpMethod="GET",UpdateTargetId="results",
InsertionMode= InsertionMode.Replace, OnSuccess="openPopup"})
<div id="dialog-detail" style="display: none">
</div>
</text>)
})
<div class="dialog"></div>
<div class="results" style="display:none;"></div>
I just get the error when I try to open the dialog box in above code. I can find Uncaught error. Might be because of the jQuery is not in order rest all it is fine. Can anyone put the above in order. Many thanks
You have one obvious issue that may cause problems. Your HTML has a div with class="results", but your selector says #results (i.e. find an element with id="results")
You could change the selector to .results (as #VeldMuijz suggested in comment), but you also have an Ajax ActionLink which requires an id as it specifies UpdateTargetId="results"
Instead add the id to your results div.
e.g. change this:
<div class="results" style="display:none;"></div>
to this:
<div id="results" style="display:none;"></div>
I also recommend with MVC projects that you put your JS code in separate JS files. Visual Studio can't debug both Razor and Javascript in the same view, but it can if the script is in its own file.