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;
};
}
});
Related
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");
});
I have more than three TextBoxes. I want to send this data as in the code. The "indeks " value is always the last click. How do I keep the index?
click:function(e) {
var item = e.itemElement.index();
indeks = item;
}
var field= "";
onl: function () {
$.ajax({
type: "GET",
cache:true,
url: MYURL,
success: function (msg, result, status, xhr) {
var obje = jQuery.parseJSON(msg)
var i = 0;
field = " ";
$('#wrapper *').filter(':input').each(function () {
if (txtvalue != "") {
if (i)
field += " and ";
field = field + "[" + obje[indeks]+ "]" $(this ).val() + "'";
i++;
}
});
});
},
As I wasn't sure if I got your question right, I prefered to comment on your topic - but now it seems that my answer helped you, so I decided to post it as an actual answer:
1st step: declare an array outside your success handler
2nd step: push the index and the value for the element into this array
3rd step: loop through all entries of the array and build your 'select' statement
Here is your edited example:
https://jsfiddle.net/Lk2373h2/1/
var clickedIndexes = [];
click:function(e) {
var item = e.itemElement.index();
indeks = item;
}
var field= "";
onl: function () {
$.ajax({
type: "GET",
cache:true,
url: MYURL,
success: function (msg, result, status, xhr) {
var obje = jQuery.parseJSON(msg)
var i = 0;
field = " ";
$('#wrapper *').filter(':input').each(function () {
$(this).attr('id', i);
var txtvalue=$(this).val();
if (i)
clickedIndexes.push({
index: indeks,
value: $(this ).val()
});
var selectString = "";
for (var u = 0; u < clickedIndexes.length; u++) {
selectString += "[" + obje[clickedIndexes[u].index].ALAN + "]" + "=" + "'" + clickedIndexes[u].value + "'";
}
field = selectString;
i++;
});
});
},
I have gallery into my project, when page loads it charge all upload images and categories like these:
As you can see, It suit images depending of selected categories. The problem is the page going to slow because it loads all images... How can I do to optimize these process? I think some like delete All categorie, but I donĀ“t know how to do my query to start for example with office categorie filter
There is my code:
function GalleryCatPopulate(url, listname, target) {
var eng = false;
if ((window.location.href.indexOf("lang=en") > 0)) {
eng = true;
}
// Getting our list items
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items? $select=Title,English",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
completeGalleryCat(data, target, eng);
},
error: function (data) {
failureGalleryCat(data, target);
}
});
}
function completeGalleryCat(data, target, eng) {
var items = data.d.results;
var prefix = "";
var sufix = "<div class='clear'></div>";
if (eng)
prefix = "<div class='filter selected' data-category='cat-all'>All</div>";
else
prefix = "<div class='filter selected' data-category='cat-all'>Todas</div>";
var menu = "";
var cat = "";
var title = "Transporte de Materiales";
console.log(title.replace(/\s/g, "_").replace(/[^\w\s]/gi, ''));
for (var item in items) {
if (eng)
cat = items[item].English;
else
cat = items[item].Title;
menu += "<div class='filter' data-category='" + cat.replace(/\s/g, "_").replace(/[^\w\s]/gi, '') +"'>"+ cat +"</div>";
}
$(target).html(prefix + menu + sufix);
}
function failureGalleryCat(data, target) {
$(target).text("There is something bad wit load images, please check console");
}
function GalleryContentPopulate(url, listname, target) {
var eng = false;
var queryGallery = "$select=Title,Description,Enlace,EncodedAbsUrl,Categoria/Title&$expand=Categoria/Title";
if ((window.location.href.indexOf("lang=en") > 0)) {
queryGallery = "$select=TitleEnglish,DescriptionEnglish,Enlace,EncodedAbsUrl,Categoria/English&$expand=Categoria/English";
eng = true;
}
// Getting our list items
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items?$top=1000&" + queryGallery,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
completeGalleryContent(data, target, eng);
},
error: function (data) {
failureGalleryContent(data, target);
}
});
}
function completeGalleryContent(data, target, eng) {
var items = data.d.results;
console.log(items);
var menu = "";
var cat = "";
for (var item in items) {
if(items[item].DescriptionEnglish==null)
items[item].DescriptionEnglish="";
if(items[item].Description==null)
items[item].Description="";
if(items[item].Categoria.results!= null && items[item].Categoria.results!= undefined && items[item].Categoria.results.length > 0){
cat =setCategories(eng,items[item].Categoria.results);
}
if (eng){
menu += "<div class='mega-entry " + cat + " cat-all' id='mega-entry-1' data-src='" + items[item].EncodedAbsUrl + "' data-width='' data-height='' data-lowsize=''><div class='mega-covercaption mega-square-bottom mega-landscape-right mega-portrait-bottom mega-red'><div class='mega-title'>" + items[item].TitleEnglish + "</div><p>" + items[item].DescriptionEnglish + "</p></div><div class='mega-coverbuttons'><div class='mega-link mega-red'></div><a class='fancybox' rel='group' href='" + items[item].EncodedAbsUrl + "' title='" + items[item].TitleEnglish + "'><div class='mega-view mega-red'></div></a></div> </div>";
}else{
menu += "<div class='mega-entry "+ cat + " cat-all' id='mega-entry-1' data-src='" + items[item].EncodedAbsUrl + "' data-width='' data-height='' data-lowsize=''><div class='mega-covercaption mega-square-bottom mega-landscape-right mega-portrait-bottom mega-red'><div class='mega-title'>" + items[item].Title + "</div><p>" + items[item].Description + "</p></div><div class='mega-coverbuttons'><div class='mega-link mega-red'></div><a class='fancybox' rel='group' href='" + items[item].EncodedAbsUrl + "' title='"+ items[item].Title +"'><div class='mega-view mega-red'></div></a></div></div>";
}
}
$(target).html(menu);
var api = $(target).megafoliopro(
{
filterChangeAnimation: "pagebottom", // fade, rotate, scale, rotatescale, pagetop, pagebottom,pagemiddle
filterChangeSpeed: 400, // Speed of Transition
filterChangeRotate: 99, // If you ue scalerotate or rotate you can set the rotation (99 = random !!)
filterChangeScale: 0.6, // Scale Animation Endparameter
delay: 20,
defaultWidth: 980,
paddingHorizontal: 10,
paddingVertical: 10,
layoutarray: [9, 11, 5, 3, 7, 12, 4, 6, 13] // Defines the Layout Types which can be used in the Gallery. 2-9 or "random". You can define more than one, like {5,2,6,4} where the first items will be orderd in layout 5, the next comming items in layout 2, the next comming items in layout 6 etc... You can use also simple {9} then all item ordered in Layout 9 type.
});
//console.log("entra");
// FANCY BOX ( LIVE BOX) WITH MEDIA SUPPORT
jQuery(".fancybox").fancybox();
//console.log("sale");
// THE FILTER FUNCTION
$('.filter').click(function () {
$('.filter').each(function () { jQuery(this).removeClass("selected") });
api.megafilter(jQuery(this).data('category'));
$(this).addClass("selected");
});
var categorySelected = getParameterByName("Category");
$("div[data-category='"+categorySelected +"']").click();
}
function failureGalleryContent(data, target) {
console.log(data);
$(target).text("Error loading parallax. Please check console for more info");
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function setCategories(boolLang, objResult){
var cat ="";
for(var item in objResult){
if(boolLang)
cat += replaceAll(" ", "_",objResult[item].English.replace(/[^\w\s]/gi, '')) + ' ';
else
cat += replaceAll(" ", "_",objResult[item].Title.replace(/[^\w\s]/gi, '')) + ' ';
}
return cat;
}
function replaceAll( find, replace,string) {
return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
function escapeRegExp(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
Thankyou in advance!
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.
my autocomplete works fine, but problem appears when I want to skip to another field in my form. When autocomplete lose focus its value disappears (also value of span that I render after this autocomplete disappears).
function initCaAutocomplete() {
$(".caSelector").autocomplete({
source: "/core/index/search-ca/ajax/1",
minLength: 2,
select: function (event, ui) {
var descId = 'desc_' + $(this).attr('id');
if ($('span#' + descId).length) {
$('span#' + descId).html(ui.item.desc);
$('span#' + descId).attr('title', ui.item.fullDesc);
} else {
$(this).after('<span title="' + (ui.item.fullDesc) + '" class="cpv_descHolder" id="' + descId + '">'
+ ui.item.fullDesc + '</span>');
}
ui.item.value = ui.item.code;
$('.tooltip', $(this).parent()).hide();
},
change: function (event, ui) {
var descId = 'desc_' + $(this).attr('id');
var inputId = $(this).attr('id');
var source = $(this).val();
$.ajax({
type : 'POST',
url : '/core/index/search-ca/ajax/1',
dataType: "text",
async : true,
data : {
term: source
},
success: function (response) {
var codes = $.parseJSON(response);
if (codes.length == 0) {
$('#' + inputId).val('');
$('span#' + descId).html('');
}
},
error: function (response) {
$('#' + inputId).val('');
$('span#' + descId).html('');
}
});
},
position: { my : "left top", at: "left bottom" }
});
}