Duplicate autodividers when selecting from sqlite - jQuery mobile - javascript

transaction.executeSql('SELECT * FROM Table1 ORDER BY date DESC', [],
function(transaction, result) {
if (result != null && result.rows != null) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
$('#records').append('<li date = "'+row['date']+'" data-rowid2="' + row['Id'] + '">' + 'test: ' + row['column1'] + '</li>').trigger('change');
}
}
},errorHandler);
transaction.executeSql('SELECT * FROM Table2 ORDER BY date DESC', [],
function(transaction, result) {
if (result != null && result.rows != null) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
$('#records').append('<li date = "'+row['date']+'" data-rowid="' + row['Id'] + '">'+ 'Test2: ' + row['column1'] +'</li>').trigger('change');
}
$("#records").listview().listview("refresh");
}
},errorHandler);
},errorHandler,nullHandler);
This is some code which selects columns from 2 different tables. The tables have two different columns called date which stores the date input. Notice the date attribute assigned to the li elements. My problem comes here:
$(document).on("pageinit", "#mypage", function(){
$("#records").listview({
autodividers: true,
autodividersSelector: function (li) {
var out = li.attr("date");
return out;
}
}).listview("refresh");
});
Now since the dates are from two different tables, two autodividers are being created even if they share the same date. For example if table1 date column had 2014-01-02 and table2 date column had 2014-01-02, two separate dividers would be created for the same date and the list elements wouldn't be shown under one. Is there a solution to this problem?
NOTE: Both the select statements append results to the same listview, they are just from different tables
EDIT: I think I have found what the issue is, but I am not sure on how to solve it. Basically, when I append those list elements, Table1 stuff takes priority and always goes first. For example if I had the list like this:
Table 1 item
Table 2 item
Then if I added another Table 1 item it will do this:
Table 1 item
Table 1 item
Table 2 item
Which is displacing the table 2 item from its original position. Is there anyway to solve this?

Related

When Pushing elements into array, same elements are repeated replacing previous one

I'm creating an Dynamic form in angular js and when I'm adding new input fields as table row,and when pushing these objects into an array, previous element is replaced with copy of new element. Keys are same but values are different and also adding 'id' key before pushing into array.
JS
else if (el.type === 4) { //table
var x = 0;
$scope.row = []; //to store KEY OF table
$scope.thead = []; //store the heading of the table | also to make row structure
$scope.myFm[el.value] = []; //store row of table [ INVOICE ] myFm.invoice
$scope.colInput = {}; //values of input of each row
$scope.colInput.id = 0;
$scope.rowIndex = 0;
//iterate over column_heading
el.column_heading.forEach(function(elem) { //objects in column_heading
$scope.row[x] = elem.val; //the object with key names of row
$scope.thead.push(elem); //column headings
x++;
})
//pusing each row to myFm[el.value] | invoice
$scope.addNew = function(rowObj) {
// $scope.rowIndex++;
console.log('ROW ', rowObj);
rowObj.id = $scope.rowIndex;
$scope.myFm[el.value].push(rowObj);
console.log("Invoice", $scope.myFm[el.value]);
$scope.rowIndex++;
console.log("ROW", rowObj);
}
var row = "<tr ng-repeat='r in myFm." + el.value + " track by id' ><td ng-repeat='i in row'><input ng-model='colInput[i]' class='form-control' placeholder='Enter {[{ i }]}'></td></tr>"
item = "<label>" + el.heading + "<button ng-click='addNew(colInput)' class='m-l-lg btn font-bold'>ADD NEW</button></label> <table class='table'><thead><th ng-repeat='th in thead'>{[{ th.name }]}</th><thead>" + "<tbody>" + row + "</tbody><table>";
}
return item
}
// adding each element from list to DOM. $compile is needed to add the modified element to DOM
$scope.data.forEach(function(el) { //traversing over json object from the server
var item = verifyItem(el);
var linkFn = $compile(item);
var content = linkFn($scope);
element.append(content);
});
// adding the submit button to DOM
var linkFn = $compile('<button type="submit" ng-click="submitFm()" class="m- t-lg m-b-lg btn btn-danger">Submit </button>');
var content = linkFn($scope);
element.append(content);
When i',m passing 'colInput' to the 'addNew' function, and adding 'id' key each time i push new object to array '$scope.myFm[el.value]', the duplicates are being created ie: the newly added is replacing the previous objects, hence i cant 'ng-repeat' it by 'track by id'.
CONSOLE
Invoice Array [ Object, Object, Object ]
these three objects have values of last pushed object.
how do i fix it.

How can mark newly added row in kendo ui grid

I am working on kendo UI grid which is located whitin tabstrip (tabstrip.select(0)). Fields for input are located in second tabstrip (tabstrip.select(1)). Crud operations working properly. My button save click event look's like this:
function saveDataMasterGrid() {
tabstrip.select(0);
var field1 = $("#field1").val();
var field2 = $("#field2").val();
var field3 = $("#field3").val();
var field4 = $("#field4").val();
var field5 = $("#field5").val();
var field6 = $("#field6").val();
var field7 = $("#field7").val();
var field8 = $("#field8").val();
var gridData = $("#gridMaster").data("kendoGrid");
var selectedRowData = gridData.dataItem($('.k-grid').find("tr.k-state-selected"));
if (selectedRowData != null || selectedRowData != undefined) {
gridData.dataSource.pushUpdate({
Id: selectedRowData.Id,
dataField1: field1,
dataField2: field2,
dataField3: field3,
dataField4: field4,
dataField5: field5,
dataField6: field6,
dataField7: field7,
dataField8: field8
});
} else {
gridData.dataSource.add({
Id: gridData.dataSource.total() + 1,
dataField1: field1,
dataField2: field2,
dataField3: field3,
dataField4: field4,
dataField5: field5,
dataField6: field6,
dataField7: field7,
dataField8: field8
});
}
How can mark newly added/edited row in kendo ui grid?
Any help appreciated. Thank you in advance.
The dataSource's method add() return the dataItem of the newly added row. So you can find the row by its uid property:
// After calling add()...
$(grid.tbody)
.find("tr").removeClass("new-row") // Remove recent added tr's .new-row classes
.filter('tr[data-uid="' + newRow.uid + '"]').addClass("new-row"); // Add class to the new row
Demo

Javascript every nth, create new row

I have a products page that I want to show 3 items in each row and then if it has more, create a new row and show more. So 3 cols per row with unlimited rows. Below is the code that I have that contains my loop which I assume the code will need to go into.
$(data).find('products').each(function() {
itemName = $(this).find('itemName').text();
itemDesc = $(this).find('itemDesc').text();
itemID = $(this).find('id').text();
items +='<div class="row-fluid">\
<div class="span3">Col 1</div>\
<div class="span3">Col 2</div>\
<div class="span3">Col 3</div>\
</div>';
count++;
});
Here is where I need to do it but I am a little stuck on how to approach this. If the count is dividable by 3 I assume it will then need to create a new row.
Thanks for any help or input you can provide.
First of all, no need to handle a count variable on your own, the .each() function already supplies an index element (as an optional argument).
With the modulus operator you can get the remainder from dividing the index by 3. Then you can tell when do you need to print the opening of the row and the ending of it.
$(data).find('products').each(function(index) {
itemName = $(this).find('itemName').text();
itemDesc = $(this).find('itemDesc').text();
itemID = $(this).find('id').text();
if ((index % 3) == 0) items += '<div class="row-fluid">';
items += '<div class="span3">Col 1</div>';
if ((index % 3) == 2) items += '</div>';
});
if (items.substr(-12) != '</div></div>') items += '</div>';
Going left field, don't! Use CSS instead.
Style up your span3 class to have a with of 30ish % with a display of inline block. That way when you decide to display 2, 4 or 60 per row you only need to change the CSS. This also opens you up to change the number of items per row with CSS media queries for diferent viewports e.g. mobile.
Further more this way you don't need to worry about closing off the row when your items returned aren't divisible by 3
On a side note, if you decide to go the CSS route, consider using <ul> and <li> instead, as semanticaly you have a list.
http://jsfiddle.net/UKQef/1/
Update Fiddle updated to demonstrate use of li and the flexibility of this approach.
You should use modulus: http://msdn.microsoft.com/en-us/library/ie/9f59bza0(v=vs.94).aspx
It gives you a remainder back from dividing two numbers so you could probably do this with something like (inside your .each):
if(!($(this).index() % 2)){
// Add your row
}
$(this).index() returns the index of your .each() and the % 2 returns the remainder of that index divided by 2 so the first 3 times this runs it'd be like this:
0 / 2 = 0 = add a row
1 / 2 = .5 = don't add a row
2 / 2 = 1 = don't add a row
Hopefully this is what you meant.
Here's what I think is a cleaner approach:
// Map each product to a cell.
var cells = $(data).find('products').map(function() {
var itemName = $(this).find('itemName').text();
var itemDesc = $(this).find('itemDesc').text();
var itemID = $(this).find('id').text();
return $('<div></div>').addClass('span3').text(itemName+' '+itemDesc+' '+itemID);
});
// Collect the cells into rows.
var rows = [];
for (var i=0, j=cells.length; i<j; i+=3) {
rows.push(
$('<div></div>')
.addClass('row-fluid')
.append(cells.slice(i,i+3))
);
}
The best approach to your issue is using jquery template. you can fetch your data in Json format by ajax request and create rows dynamically by jquery template:
<script src="jquery.tmpl.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var data = [
{ name: "Astor", product: "astor", stocklevel: "10", price: 2.99},
{ name: "Daffodil", product: "daffodil", stocklevel: "12", price: 1.99},
{ name: "Rose", product: "rose", stocklevel: "2", price: 4.99},
{ name: "Peony", product: "peony", stocklevel: "0", price: 1.50},
{ name: "Primula", product: "primula", stocklevel: "1", price: 3.12},
{ name: "Snowdrop", product: "snowdrop", stocklevel: "15", price: 0.99},
];
$('#flowerTmpl').tmpl(data).appendTo('#row1');
});
</script>
<script id="flowerTmpl" type="text/x-jquery-tmpl">
<div class="dcell">
<img src="${product}.png"/>
<label for="${product}">${name}:</label>
<input name="${product}" data-price="${price}" data-stock="${stocklevel}"
value="0" required />
</div>
</script>
Html:
<div id="row1" class="drow"></div>
var $products = $(data).find('products');
var num_of_rows = Math.ceil($products.length/3)
//Create your rows here each row should have an id = "row" + it's index
$products.each(function(i,val){
var row_index = Math.ceil(i/3)
$('#row' + row_index).append("<div>Col"+i%3+"</div>")
});
Something like that should work

MVC 4 - Cascading Dropdown Lists - Issue with Ajax JavaScript Call

I have an MVC 4 app with a View containing two dropdown lists. The user selects a value in the first dropdown and then an Ajax call is made to populate the second dropdown based on the contents of the first.
My JavaScript code looks as follows and gets called when the user selects an item in the first dropdown:
function GetAutoModel(_manufacturerId) {
var autoSellerListingId = document.getElementById("AutoSellerListingId").value;
$.ajax({
url: "/AutoSellerListing/GetAutoModel/",
data: { manufacturerId: _manufacturerId, autoSellerListingId: autoSellerListingId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>-- Select --</option>";
for (var x = 0; x < data.length; x++) {
**if (data[x].Selected) {**
markup += "<option selected='selected' value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
else
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$('#autoModel').html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
The Ajax call works correctly. However, the data that gets returned for the second dropdown contains a selected item and I'm trying to detect the selected item (via the 'if' statement), and render the HTML appropriately. The problem is that 'Selected' doesn't seem to be a property of 'data' because each value evaluates to false, even though one of the values is true.
Am I doing something wrong? Or is there a better way to do this?
The following is the controller code:
[HttpPost]
public ActionResult GetAutoModel(int manufacturerId, int autoSellerListingId)
{
int modelId = 0;
// Get all the models associated with the target manufacturer
List<AutoModel> modelList = this._AutoLogic.GetModelListByManufacturer(manufacturerId);
// If this is an existing listing, get the auto model Id value the seller selected.
if (autoSellerListingId > 0)
modelId = this._systemLogic.GetItem<AutoSellerListing>(row => row.AutoSellerListingId == autoSellerListingId).AutoModel.AutoModelId;
// Convert all the model data to a SelectList object
SelectList returnList = new SelectList(modelList, "AutoModelId", "Description");
// Now find the selected model in the list and set it to selected.
foreach (var item in returnList)
{
if (item.Value == modelId.ToString())
item.Selected = true;
}
return Json(returnList);
}
Try this instead (add modelId to constructor of SelectList, and remove the foreach block):
// Convert all the model data to a SelectList object
SelectList returnList = new SelectList(modelList, "AutoModelId", "Description", modelId);
return Json(returnList);

Jquery: Inline editing for tables inner rows

I am new to jquery and datatable.
I have developed the editable datatable for "contacts", where each row represents a contact.
Each "contact" has some "actions" associated with them.
When the user clicks on a particular "contact" the associated "actions" are displayed as additional rows under that particular contact.
Now I want to make both the "contact" row and the "action" rows editable. I have used "jEditable" plugin and can get the "contact" row as editable and not the "action".
Any idea, or help will be greatly appreciated.
userInfo = "<table id='mycontacttable'><thead><tr><th></th><th>FirstName</th><th>FamilyName</th></tr></thead><tbody> ";
/*constructing the Contact table, at this stage without the actions.*/
for(i =0 ; i < response.result.length ; i++){
var contactid=response.result[i].contactID;
userInfo += "<tr><td>"+
"<img src=\"../javascript/datatables/media/images/details_open.png\" rel="+contactid+" alt=\"expand/collapse\"></td>"+
"<td>"+ response.result[i].givenName + "</td><td>" + response.result[i].familyName+"</td></tr> ";
}
userInfo += "</tbody></table> ";
$('#info').html("The following are your contacts. " + userInfo);
/*setting the sortable and unsortable columns*/
oTable= $('#mycontacttable').dataTable({
"iDisplayLength": 25,
"bSort": true,
"aoColumns": [
{ "bSortable": false },//Disable sorting on this column
null,
null
]
}).makeEditable();
/*clicking a particular row in the table mycontacttable, and assigning the click event*/
$('#mycontacttable tbody td img').live("click",function () {
var nTr = this.parentNode.parentNode;
if (this.src.match('details_close')) {
/* This row is already open - close it */
this.src = "../javascript/datatables/media/images/details_open.png";
oTable.fnClose(nTr);
}
else {
/* Open this row */
this.src = "../javascript/datatables/media/images/details_close.png";
var contact_id = $(this).attr("rel");/*contact id of a particular row that is clicked is stored in the variable contact_id*/
/*creating a sub table*/
action_sub_table = "<table id='submycontacttable'>"
for(i =0 ; i < response.result.length ; i++){
var contactid=response.result[i].contactID;
if(contact_id==contactid){
/*Iterating through each action of the contact, and constructing a sub table row for it*/
for(count=0;count<response.result[i].actionSet.length;count++){
action_sub_table += "<tr><td>"+response.result[i].actionSet[count].actionID+" </td><td>"+
response.result[i].actionSet[count].actionDueDate+"</td><td>" +
response.result[i].actionSet[count].actionNote+"</td></tr>";
}
}
}
action_sub_table +="</tablr>"; /*Construction of the subtable complete*/
oTable.fnOpen(nTr, action_sub_table, "info_row" );
}
});
you can try jqGrid instead, I suppose that would be perfect in your case http://www.trirand.com/blog/

Categories