How Kendo grid select row get the selected userID? - html

Hi i need some help for to get the select row id as i realize i am able to get my ajax from my response however is there a way where i select the row i can display the id selected one ?
Updated by using the new onchange i have make a selected id however i got error still
var dataSource = new kendo.data.DataSource({
read: {
url: "https://ecoexchange.dscloud.me:8090/api/get",
dataType: "JSON",
method: "GET",
headers: {
query: "UserGet(1)",
// Gets the apikey from the sessionStorage
apikey: sessionStorage.getItem("apikey")
}
},
});
$("#user-list").kendoGrid({
dataSource: dataSource,
height: $(window).height() - $("#user-list").position()["top"] - 130,
selectable: "single, row",
change: function(e) {
var selectedRows = this.select();
var selectedDataItems = [];
for (var i = 0; i < selectedRows.length; i++) {
var dataItem = this.dataItem(selectedRows[i]);
selectedDataItems.push(dataItem);
}
// selectedDataItems contains all selected data items
/* The result can be observed in the DevTools(F12) console of the browser. */
if (selectedDataItems && selectedDataItems.length > 0) {
$("#selection")[0].innerHTML = selectedDataItems[0].UserID;
}
},
// width: $(window).width()-$("#customer-list").position()["width"]-10,
//pageSize: 10,
scrollable: {
endless: true,
},
columns: [
{
field: "",
title: "Profile",
headerAttributes: {
"class": "k-text-center"
},
width: 150
},
{
field: "",
title: "User Name",
},
],
});
$("#user-list tbody").on("click", "tr", function(e) {
const btns = $('.select-row');
var rowElement = this;
var row = $(rowElement);
var grid = $("#user-list").getKendoGrid();
if (row.hasClass("k-state-selected")) {
var selected = grid.select();
selected = $.grep(selected, function(x) {
var itemToRemove = grid.dataItem(row);
var currentItem = grid.dataItem(x);
return itemToRemove != currentItem
})
btns.prop('disabled', true).removeClass('disabled dark');
grid.clearSelection();
grid.select(selected);
e.stopPropagation();
} else {
grid.select(row)
e.stopPropagation();
btns.prop('disabled', false).removeClass('disabled dark');
}
});
I am calling my ajax to kendo grid where kendo grid created the grid and the selected row
This is how the page look like
However i have no idea how to select the row display the userID display where then if this is selected when press view details the information be pass into there
This is the response example
[
{
"UserID": 1,
"Name": "Kelyn Wong",
"Username": "kelynwong",
"Email": "kelynwonget#gmail.com",
"Picture": null,
"UserRole": "Approving Admin"
},
{
"UserID": 2,
"Name": "Kai Jie",
"Username": "kaijie",
"Email": "test#gmail.com",
"Picture": null,
"UserRole": "Admin"
},
This is how the row selected look like when the user select the row
This the whole code from body to script from using ajax to kendo grid
< script >
/* Call the ajax to load to load to #customer-list tbody */
$.ajax({
url: "https://ecoexchange.dscloud.me:8090/api/get",
method: "GET",
// In this case, we are going to use headers as
headers: {
// The query you're planning to call
// i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
query: "UserGet(0)",
// Gets the apikey from the sessionStorage
apikey: sessionStorage.getItem("apikey")
},
success: function(data, xhr, textStatus) {
//console.log(data)
const buildTable = data => {
const table = document.querySelector("#user-list tbody");
for (let i = 0; i < data.length; i++) {
let row =
`
<tr>
<td class="cell-user-name"style="padding-left: 20px;"><img src = "${data[i].Picture}" class="picture" width="100px" height="100px" onError="this.onerror=null;this.src='../../assets/images/placeholder-avatar.jpg';" ></img></td>
<td class="cell-user-name" style="padding-right: 80px; padding-top: 10px; font-weight: bold; font-size: 18px;">${data[i].Name}</td>
</tr>
`;
table.insertAdjacentHTML('beforeEnd', row);
}
};
// Fetch method
const getData = async(url) => {
const response = await fetch(url, {
method: 'GET',
headers: {
query: "UserGet(0)",
// Gets the apikey from the sessionStorage
apikey: sessionStorage.getItem("apikey")
}
});
const json = await response.json();
$("#loading-container").hide();
return buildTable(json);
};
/*Error GET http://127.0.0.1:5501/testEnv/view/public/manageCustomers/null 404 (Not Found) */
/* But code are able to fetch the data */
getData("https://ecoexchange.dscloud.me:8090/api/get")
},
error: function(xhr, textStatus, err) {
console.log(err);
}
});
$(window).on("resize", function(e) {
console.log("width:", $("#user-list").width(), "height:", $("#user-list").height())
});
$("#user-list").kendoGrid({
height: $(window).height() - $("#user-list").position()["top"] - 130,
selectable: "single",
// width: $(window).width()-$("#customer-list").position()["width"]-10,
//pageSize: 10,
scrollable: {
endless: true,
},
columns: [
{
field: "",
title: "Profile",
headerAttributes: {
"class": "k-text-center"
},
width: 150
},
{
field: "",
title: "User Name",
},
],
});
$("#user-list tbody").on("click", "tr", function(e) {
const btns = $('.select-row');
var rowElement = this;
var row = $(rowElement);
var grid = $("#user-list").getKendoGrid();
if (row.hasClass("k-state-selected")) {
var selected = grid.select();
selected = $.grep(selected, function(x) {
var itemToRemove = grid.dataItem(row);
var currentItem = grid.dataItem(x);
return itemToRemove != currentItem
})
btns.prop('disabled', true).removeClass('disabled dark');
grid.clearSelection();
grid.select(selected);
e.stopPropagation();
} else {
grid.select(row)
e.stopPropagation();
btns.prop('disabled', false).removeClass('disabled dark');
}
});
// <!-- Search bar function -->
$("#search-user-name").on("keyup change", function() {
var usernames = $("#search-user-name").val().toLowerCase();
//console.log(usernames);
if (usernames == "") {
$('#user-list tbody tr td.cell-user-name').parent().show();
} else {
$("#user-list tbody tr").filter(function() {
var usernameText = $(this).children("td.cell-user-name").text().toLowerCase();
$(this).toggle(
(usernameText.indexOf(usernames) >= 0)
);
})
};
})
<
/script>
<!-- the white rectange body contain-->
<div id="container-body">
<div class="col-12">
<br />
<div class="input-group">
<!-- Length of the search bar -->
<div class="col-md-10">
<!-- Search bar components -->
<span id="search-icon" class="fa fa-search search-icon-span"></span>
<input class="search-input form-control" placeholder="Name" type="text" name="User Name" id="search-user-name">
</div>
<!-- button all of it-->
<fieldset class='btn-group'>
<button onclick="window.location.href='addUsers.html'" id="add" type="button" class="btn btn-primary btn custom mr-1 mb-2" style="border-radius: 5px;">Add </button>
<button onclick="window.location.href=''" id="edit" type="button" class=" btn-primary btn custom mr-1 mb-2 disabled select-row" style="border-radius: 5px; margin-left: 5px;" disabled>View Details</button>
</fieldset>
<div class="col-md-12">
<div class="table-responsive" style="overflow:hidden; padding-top: 20px;">
<table id="user-list" class="table">
<!-- Loading Spinner Div -->
<div id="loading-container">
<p>Fetching all users data...</p>
<div id="loading-spinner">
</div>
<tbody>
</tbody>
</table>
</div>
</div>

You can use the change event of the Kendo Grid to get the selected row. See the snippet below for a demo from the Kendo documentation.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2021.3.1207/styles/kendo.default-v2.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2021.3.1207/js/kendo.all.min.js"></script>
</head>
<body>
<label>
Selection: <span id="selection"></span>
</label>
<div id="grid"></div>
<script>
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "https://demos.telerik.com/kendo-ui/service/products",
dataType: "jsonp"
}
},
pageSize: 10
});
$("#grid").kendoGrid({
dataSource: dataSource,
selectable: "single, row",
change: function(e) {
console.log("change", this.dataItem(this.select()[0]));
const selection = this.select();
if (selection && selection.length > 0) {
$("#selection")[0].innerHTML = this.dataItem(selection[0]).ProductID;
}
}
});
</script>
</body>
</html>

Related

how to fix datatable responsive bootstrap 5 delete button not working

I have a datatable responsive bootstrap 5 delete & Edit button working very good befor expended the row or click + on the table,
like this pic, after i click + and expended the table on mobile screen not workin like this pic see here. I'm not programmer and trying to do my page by Google Script, thux in advance
the code:
* Prevent forms from submitting.
* */
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener("load", functionInit, true);
/**
* INITIALIZE FUNCTIONS ONLOAD
* */
function functionInit(){
preventFormSubmit();
getLastTenRows();
};
/**
* HANDLE FORM SUBMISSION
* */
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(createTable).processForm(formObject);
// setTimeout(function() {$('#myModal').modal('hide');}, 10000);
document.getElementById("message").innerHTML = "<div class='alert alert-warning' role='alert'>Added the record successfully.</div>";
document.getElementById("myForm").reset();
}
/**
* Clear form when pop-up is closed.
* */
function clearForm() {
document.getElementById("message").innerHTML = "";
document.getElementById("myForm").reset();
}
google.script.run.withSuccessHandler(createTable).getAllData();
document.getElementById('resp-spinner5').classList.remove("d-none");
document.getElementById('resp-spinner6').classList.remove("d-none");
document.getElementById('resp-spinner7').classList.remove("d-none");
document.getElementById('resp-spinner8').classList.remove("d-none");
document.getElementById('resp-spinner9').classList.remove("d-none");
document.getElementById('resp-spinner10').classList.remove("d-none");
function createTable(dataArray) {
$('#btn-close').click()
$(document).ready(function(){
document.getElementById('resp-spinner5').classList.add("d-none");
document.getElementById('resp-spinner6').classList.add("d-none");
document.getElementById('resp-spinner7').classList.add("d-none");
document.getElementById('resp-spinner8').classList.add("d-none");
document.getElementById('resp-spinner9').classList.add("d-none");
document.getElementById('resp-spinner10').classList.add("d-none");
$('#dataTable').DataTable({
//data: dataArray,
data: dataArray.slice(1),
columns: [
{ title: "ID" },
{ title: "Name" },
{ title: "State" },
{ title: "Date" },
{ title: "Mobile No" },
{ title: "Address" },
{ title: "Remarks" },
{ title: "Edit", "render": function (data,type, row, meta){
return "<button type='button' class='btn btn-outline-warning btn-xs editBtn' data-toggle='modal' data-target='#myModal' onclick='editData(this);'><i class='fa fa-edit'></i></button>";
}
},
{ title: "Delete", "render": function (data,type){
return "<button type='button' class='btn btn-outline-danger btn-xs deleteBtn' onclick='deleteData(this);'><i class='fa fa-trash''></i></button>";
}
},
],
"fnRowCallback": function(nRow, aData, iDisplayIndex) {
nRow.setAttribute('id',aData[0]);
},
// "ordering": false,
destroy:true,
responsive:true,
lengthMenu: [
[5, 10, 25, 50, 100, -1 ],
['5', '10', '25', '50','100', 'All' ]
],
order: [[2, "asc"], [2, "asc"], ],
});
});
}
/**
* DELETE DATA
* */
function deleteData(el) {
Swal.fire({
position:'top',
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
cancelButtonText: 'Cencel',
confirmButtonText: 'Ok'
}).then((result) => {
if (result.isConfirmed) {
Swal.fire(
'Deleted!',
'Your file has been deleted.',
)}
if (result.isDismissed) {
swal.fire("Cancelled!", "Files not deleted!", "warning");
console.log("Doing Nothing")
var recordId = el.parentNode.parentNode.cells[0].innerHTML;
google.script.run.withSuccessHandler(createTable).deleteData(recordId);
}
});
}
/**
* EDIT DATA
* https://stackoverflow.com/a/32377357/2391195
* */
function editData(el){
var recordId = el.parentNode.parentNode.cells[0].innerHTML;
google.script.run.withSuccessHandler(populateForm).getRecordById(recordId);
}
/**
* POPULATE FORM
* */
function populateForm(records){
document.getElementById('RecId').value = records[0][0];
document.getElementById('name').value = records[0][1];
document.getElementById('State').value = records[0][2];
document.getElementById('date').value = records[0][3];
document.getElementById('data1').value = records[0][4];
document.getElementById('data2').value = records[0][5];
document.getElementById('data3').value = records[0][6];
document.getElementById("message").innerHTML = "<div class='alert alert-warning' role='alert'>Update Record [ID: "+records[0][0]+"]</div>";
}
/**
* RETRIVE DATA FROM GOOGLE SHEET FOR State DROPDOWN
* */
function createStateDropdown() {
//SUBMIT YOUR DATA RANGE FOR DROPDOWN AS THE PARAMETER
//Change to your sheet name and data range.
google.script.run.withSuccessHandler(StateDropDown).getDropdownList("State!A1:A4");
}
/**
* POPULATE State DROPDOWNS
* Ref: https://stackoverflow.com/a/53771955/2391195
* */
function StateDropDown(values) {
var list = document.getElementById('State');
for (var i = 0; i < values.length; i++) {
var option = document.createElement("option");
option.value = values[i];
option.text = values[i];
list.appendChild(option);
}
}
function loading(){
window.addEventListener("load", functionInit, false);
window.addEventListener("load", preventFormSubmitSearch, true);
}
</script>
<script>
$('#datatable').DataTable()
.columns.adjust()
.responsive.recalc();
<script>
$(document).ready(function () {
alert("Test");
});
</script>
</script>
<script src="~/lib/jquery/dist/jquery.js"></script>
i hope can sol

Quill strips out simple html when dangerouslyPasteHTML into editor

<style>
#editor-container {
height: 375px;
}
.link {
color:blue;
}
</style>
<div id="editor-container">
This is a test
</div>
<script type="text/javascript">
var quill = new Quill('#editor-container', {
modules: {
toolbar: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline'],
['image', 'code-block']
]
},
placeholder: 'Compose an epic...',
theme: 'bubble' // or 'bubble'
});
quill.clipboard.dangerouslyPasteHTML(5, "<span class=\"link\" data-test=\"test\">testing</span>", "silent");
</script>
MVCE - https://codepen.io/anon/pen/QMQMee
The HTML get stripped out despite being pretty harmless (this will be handled better later).
My current plan, due to the way Quill does not allow pasted html, is (As part of a click action on the mentioned person's name):
$("#tag-selectable-users-list li").on("click",
function() {
var $this = $(this);
var startIndex = $this.data("data-start-index");
var userName = $this.data("data-user-name");
var userId = $this.data("data-user-id");
var taggedUserIds = $("#hiddenTaggedUsers");
taggedUserIds.val((taggedUserIds.val()||"") + ";" + userId);
var delta = [];
if (startIndex > 0) {
//retain up to the tag start
delta.push({ retain: parseInt(startIndex) });
}
//delete the junk
delta.push({ delete: tagStatus.Total.length });
//insert the new characters
delta.push({
insert: "##" + userName,
attributes: {
color: "blue",
underline: "true"
}
});
//insert a blank space to end the span
delta.push({ insert: " " });
quill.updateContents(delta,
'api');
});
}

How do I register the on-tap in a paper-icon-button in an ag-grid cell renderer?

I am working on adding ajax call to paper-icon-buttons that are rendered in an ag-grid cell renderer. Here is the script in my custom polymer component. The paper-icon-buttons do show up and clicking on them causes the ripple, but the functions in the on-tap are not being called.
Is there a better way to add the paper-icon-button entries to the cell? How can I add the registration of the on-tap properly?
Thank you!
<script>
function sourceRenderer(params) {
if (params.value)
return '<span>' + params.value + ''
else
return null;
}
function innerCellRendererA(params) {
var imageFullUrl = '/images/' + params.data.type + '.png';
if (params.data.type == 'entity') {
var entityUrl = '/analyze/' + params.data.asource + '/' + params.data.amodel + '/' + params.data.sourceName;
return '<img src="'+imageFullUrl+'" style="padding-left: 4px;" /> ' + params.data.name + ' (' + params.data.sourceName + ')';
}
else if (params.data.type == 'model') {
var entityUrl = '/harvest/' + params.data.asource + '/' + params.data.name;
return '<img src="'+imageFullUrl+'" style="padding-left: 4px;" /> ' + params.data.name + '';
}
else
return '<paper-icon-button src="'+imageFullUrl+'" on-tap="testjdbc" data-args="'+params.data.classname+'~~'+params.data.url+'~~'+params.data.username+'~~'+params.data.password+'"></paper-icon-button> ' +
'<paper-icon-button src="/images/database_export.svg" on-tap="harvestmodel" data-args="'+params.data.classname+'~~'+params.data.url+'~~'+params.data.username+'~~'+params.data.password+'"></paper-icon-button> ' + params.data.name;
}
Polymer({
is: 'easymetahub-analyze',
properties: {
sourcelist: {
type: Array,
notify: true
}
},
testjdbc: function(e){
alert('Foo');
var args = e.target.getAttribute('data-args').split('~~');
},
harvestmodel: function(e){
alert('Bar');
var args = e.target.getAttribute('data-args').split('~~');
},
handleData: function(e) {
var resp = e.detail.response;
this.sourcelist = resp;
},
ready: function() {
},
attached: function() {
agGrid.initialiseAgGridWithWebComponents();
var columnDefs = [
{
headerName: "Name",
'field': 'name',
width: 350,
cellRenderer: 'group',
sort: "asc",
cellRendererParams: {
innerRenderer: innerCellRendererA
}
},
{headerName: "Database Type", field: "databasetype", width: 120 },
{headerName: "URL", width: 250, field: "url" },
{headerName: "User Name", field: "username", width: 120 }
];
var gridOptions = {
columnDefs: columnDefs,
enableColResize: true,
rowHeight: 36,
enableSorting: true,
getNodeChildDetails: function(file) {
if (file.children) {
return {
group: true,
children: file.children,
expanded: file.open,
field: 'name',
key: file.name
};
} else {
return null;
}
},
onGridReady: function(params) {
params.api.sizeColumnsToFit();
}
};
this.$.myGrid.setGridOptions(gridOptions);
var eInput = this.$.quickFilterInput;
eInput.addEventListener("input", function () {
var text = eInput.value;
gridOptions.api.setQuickFilter(text);
});
},
detached: function() {
this.$.myGrid.api.destroy();
}
});
</script>
agGrid's grid options has a property for a callback -- onModelUpdated -- that is called when new rows are added to the grid.
attached: function() {
var self = this;
var gridOptions = {
...
onModelUpdated: function(e) {
self._bindGridIconTap();
}
};
}
You could use this event to query the grid for its paper-icon-buttons and add their on-tap attributes as event handlers.
_bindGridIconTap: function() {
this._bindActionsOnGrid('paper-icon-button', 'tap');
},
_bindActionsOnGrid: function(selector, eventName) {
var self = this;
var buttons = this.$.myGrid.querySelectorAll(selector);
buttons.forEach(function(b) {
self._bindEvent(b, eventName);
});
},
_bindEvent: function(el, eventName) {
var self = this;
var methodName = el.getAttribute('on-' + eventName);
var method = self[methodName];
if (method) {
el.addEventListener(eventName, function(e) {
method(e);
e.stopPropagation();
e.preventDefault();
return false;
});
} else {
console.warn(el.localName, 'listener method not found:', methodName);
}
}
plunker
Note you have a bug in:
var args = e.target.getAttribute('data-args').split('~~');
In a tap event for paper-icon-button, e.target is the icon image. You actually want e.currentTarget, which I've done for you in the Plunker.

How to Rebuild owl carousel on ng-click in angular.js?

I am facing some serious issue, I used owl carousel in angular.js. Its working fine on first time. Later i have a buttons on the same page i want to rebuild the owl carousel on that particular button with new data. here is my controller and html code.
.directive('riskcarousel', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
var syncPosition = function (event) {
var nav = this;
var body = $('#risk_body').data('owlCarousel');
$timeout(function () {
body.to(nav._current);
scope.setPhaBackgroundColor(nav._current);
}, 1000);
};
//console.log(owlCarousel,"Smartdata");
var owl = $(element.parent()).owlCarousel({
items: 3,
nav: false,
dots: false,
center: true,
responsive: {
0: {
items: 3,
nav: false
},
600: {
items: 3,
nav: false
},
1000: {
items: 3,
nav: false
}
},
onDragged: syncPosition
});
//owl.data().owlCarousel.addItem('<a class="item link center-owl-item" style="background-color: transparent;"></a>', owl.data().owlCarousel.num.items - 1);
//owl.data().owlCarousel.addItem('<a class="item link center-owl-item" style="background-color: transparent;"></a>', owl.data().owlCarousel.num.items - 1);
//owl.data().owlCarousel.reset(owl.data().owlCarousel.num.items-1);
$timeout(function () {
owl.data().owlCarousel.to(0);
//owl.data().owlCarousel.removeItem(owl.data().owlCarousel.num.items-1);
//owl.data().owlCarousel.removeItem(owl.data().owlCarousel.num.items-1);
}, 10);
}
element.on('click', function () {
//$('.owl-item').removeClass('selected-item');
//element.parent().addClass('selected-item');
alert('hello');
var index = element.attr('data-index');
var nav = $('#risk_nav').data('owlCarousel');
var body = $('#risk_body').data('owlCarousel');
$timeout(function () {
nav.to(index);
body.to(index);
scope.setPhaBackgroundColor(index);
}, 10);
});
}
}
})
.directive('riskCarouselBody', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
var syncPosition = function (event) {
var nav = $('#risk_nav').data('owlCarousel');
var body = this;
$timeout(function () {
nav.to(body._current);
scope.setPhaBackgroundColor(body._current);
}, 10);
};
var owl = $(element.parent()).owlCarousel({
items: 1,
nav: false,
dots: false,
responsive: {
0: {
items: 1,
nav: false
},
600: {
items: 1,
nav: false
},
1000: {
items: 1,
nav: false
}
},
onDragged: syncPosition
});
}
}
}
})
Html code
<div ng-repeat="s_disease in sub_diseases"
style="float: left; border-radius: 50%; height: 50px; width: 50px; margin: 2px;"
ng-class="[s_disease.background , s_disease.class, 'sub_diseases_clicked']">
<img ng-src="http://localhost:3000/uploads/{{s_disease.icon}}" style="width: 50px; height: 50px"
ng-click="getSubDiseasesPHA(s_disease.id) ">
</div>
</div>
<div class="pha-carousel">
<div class="pha-back">
<a class="carousel-icon" href="#/qsummary"><i class="ion-chevron-left"
style="color: rgba(255, 255, 255, 1);"></i></a>
</div>
<div class="owl-carousel" id="risk_nav">
<a class="item link center-owl-item" data-index="{{$index}}" ng-repeat="pha in phas"
ng-class="[pha.background, pha.class]"
ng-style="pha.key_string=='qscore' && {'background-color': pha.background}"
riskcarousel><h1 style="white-space:normal !important;">{{pha.health_area}}</h1></a>
</div>
</div>
I made a carousel initialize function and calls when controller initialize
$scope.initializeCaraousel = function () {
//Check if already carousel made then destroy
if (typeof $("#sync1").data('owlCarousel') != 'undefined') {
$("#sync1").data('owlCarousel').destroy();
$('#sync2').data('owlCarousel').destroy();
}
var sync1 = $("#sync1");
var sync2 = $("#sync2");
sync1.owlCarousel({
singleItem : true,
slideSpeed : 1000,
navigation: true,
pagination:false,
afterAction : syncPosition,
responsiveRefreshRate : 200
});
sync2.owlCarousel({
items : 3,
itemsDesktop : [1199,10],
itemsDesktopSmall : [979,10],
itemsTablet : [768,8],
itemsMobile : [479,4],
pagination:false,
responsiveRefreshRate : 100,
afterInit : function(el){
el.find(".owl-item").eq(0).addClass("synced");
}
});
function syncPosition(el){
var current = this.currentItem;
console.log(current);
$("#sync2")
.find(".owl-item")
.removeClass("synced")
.eq(current)
.addClass("synced")
if($("#sync2").data("owlCarousel") !== undefined){
center(current)
}
// code for smooth transition
this.owl.owlItems.removeClass('smooth-slide');
$(this.owl.owlItems[this.owl.currentItem]).addClass('smooth-slide');
}
$("#sync2").on("click", ".owl-item", function(e){
// e.preventDefault();
var id = $(this).attr("id");
//console.log(id);
var index = parseInt(e.target.id);
//console.log(index);
sync1.trigger("owl.goTo", index);
});
function center(number){
var sync2visible = sync2.data("owlCarousel").owl.visibleItems;
var num = number;
var found = false;
for(var i in sync2visible){
if(num === sync2visible[i]){
var found = true;
}
}
if(found===false){
if(num>sync2visible[sync2visible.length-1]){
sync2.trigger("owl.goTo", num - sync2visible.length+2)
}else{
if(num - 1 === -1){
num = 0;
}
sync2.trigger("owl.goTo", num);
}
} else if(num === sync2visible[sync2visible.length-1]){
sync2.trigger("owl.goTo", sync2visible[1])
} else if(num === sync2visible[0]){
sync2.trigger("owl.goTo", num-1)
}
}
}

How to append the content dynamically at swipe the page in jquery mobile

I am trying to append the content dynamically when i swipe the page i try the following method
JS part:
var i = 2;
$(document).on('pagebeforeshow ', function () {
loadPage(i);
});
function loadPage(index) {
$.ajax({
url: "connection.php",
type: "POST",
datatype: 'json',
data: {
"pageIndex": index
},
beforeSend: function (a, b) {
$.mobile.showPageLoadingMsg();
},
success: function (result) {
var a = $.parseJSON(result);
$('.primarycontent').append('<img src="images/' + a.report + '" />');
$.each(a.controls, function (j, row) {
if (row.controltype == "dropdown") {
var selectarray = row.controlvalues.split(",");
addDropDown(selectarray, j);
}
if (row.controltype == "button") {
var urlvalue = row.controlvalues;
addButton(urlvalue, j);
}
});
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
error: function (request, error) {
alert('Network error has occurred please try again!');
}
});
var dropdown_array = [];
function addDropDown(values, count) {
var selectElm = $("<select/>");
selectElm.attr({
'name': 'dropdown-' + count,
'id': 'dropdown-' + count
}).appendTo('#dropdownplace');
dropdown_array.push('dropdown-' + count);
$.each(values, function (a, b) {
selectElm.append($("<option/>").attr("value", b).text(b)).appendTo('#dropdown-' + count);
});
$('select').selectmenu();
return;
}
function addButton(url, count) {
for (m = 0; m < dropdown_array.length; m++) {
var selected_dropdown = $("#" + dropdown_array[m]);
// alert(selected_dropdown.val());
}
$('#buttonPlaceHolder').append('Refresh');
// refresh jQM controls
$('#home2').trigger('create');
//myselect[0].selectedIndex = 3;
//var button = $("<a/>");
//button.attr({'href':url+});
return;
}
}
$(document).off('swipeleft').on('swipeleft', 'div[data-role="page"]', function (event) {
if (event.handled !== true) // This will prevent event triggering more then once
{
alert(hi);
var nextpage = $.mobile.activePage.next('div[data-role="page"]');
// swipe using id of next page if exists
if (nextpage.length > 0) {
alert(hi);
i++;
$.mobile.changePage(nextpage, {
transition: "slide",
reverse: false
}, true, true);
loadPage(i++);
}
event.handled = true;
}
return false;
});
$(document).off('swiperight').on('swiperight', 'div[data-role="page"]', function (event) {
if (event.handled !== true) // This will prevent event triggering more then once
{
var prevpage = $(this).prev('article[data-role="page"]');
if (prevpage.length > 0) {
$.mobile.changePage(prevpage, {
transition: "slide",
reverse: true
}, true, true);
}
event.handled = true;
}
return false;
});
index.html:
<div data-role="page" id="home2">
<!-- Header -->
<div data-role="header" class="header1" data-theme="b">
<h1>Group:Group Name</h1>
<a data-role="button" data-rel="back" data-icon="arrow-l">Search</a>
</div>
<!-- Content -->
<div data-role="content">
<div>
<div id="dropdownplace"></div>
<div id="buttonPlaceHolder"></div>
<div class="primarycontent"></div>
</div>
</div>
<!-- Footer -->
<div data-role="footer" data-id="persistantFooter" data-position="fixed" class="nav-glyphish-example">
<div data-role="navbar" class="nav-glyphish-example" data-grid="c">
<ul>
<li>Home
</li>
<li>Feeds
</li>
<li>Secure
</li>
<li>Contacts
</li>
</ul>
</div>
</div>
</div>
now i want to append the content when i swipe left or right i send the index value to my connection.php.I want to like this demo from this link
Thanks