AngularJS: Using If condition in text input - asp.net-mvc

I have an input type as text to select dates and I want that Its default value should be the earliest amongst the JSON data having following structure:
testData=
{
"name":"ABC", transactions:[
{"tranid":01,"trandate":"01/02/2010"},
{"tranid":02,"trandate":"01/02/2012"}
]
}
I want to iterate through transactions and Dispay the earliest date in the text input(i.e 01/02/2010)
Please assist how to do it in angular.

Hi please see here: http://jsbin.com/reyog/1/edit
function finderliest()
{
angular.forEach(testData.transactions, function(transaction){
if($scope.erliest === undefined || transaction.trandate < $scope.erliest ){
$scope.erliest = transaction.trandate;
}
});
};

var len=testData.transactions.trandate.length;
if(len>0)
{
for (i=0;i<len;i++)
{
for (j=1;j<len;j++)
{
var dateone=testData.transactions.trandate[i];
var datetwo=testData.transactions.trandate[j];
//(use this logic or else logic whichever you like) http://www.c-sharpcorner.com/UploadFile/8911c4/how-to-compare-two-dates-using-javascript/
}
}
}

Related

Twilio - How to proper return activities on encoding ISO-8859-1?

I'm facing a problem to work with activities that uses accents (diacritics). If I create an Activity like "Consolação", when I call the function to fill my activities array, the returns shows me something like:
{ ... //many attributes
"friendlyName": "Concei??o",
...
}
This is how I get all my activities:
worker = new Twilio.TaskRouter.Worker(workerToken)
function loadActivitySids() {
worker.activities.fetch(function(error, activityList) {
if ( error ) {
console.log(error.message);
return;
}
var activities = activityList.data;
activities.forEach(function(activity) {
activitySids[activity.friendlyName] = activity.sid;
});
});
}
Is there anyway that allow me create activities using accents?

Select2 - Show/Hide div based on selection

I am trying to have a div show if an option is selected using the Select2 plug in.
I tried using the following code but it does not work:
$(document).ready(function() {
var h = $(".shipment-details--other-description");
$("#shipment-details-select-pacakage-types").change(function() {
if (this.checked && this.value == "Other") {
h.show();
} else {
h.hide();
}
}).change()
});
The div is being hid but not being shown if the Other option is selected.
Is there a different way to do this with Select2?
Edit: Forgot to mention that this a multiple select field. Also, adjusted the code and took out the this.checked as that was for a check field.
try to create a new css class, is-hidden{ display:none;}
$(document).ready(function() {
var h = $(".shipment-details--other-description");
$("#shipment-details-select-pacakage-types").change(function() {
if (this.checked && this.value == "Other") {
h.addClass('is-hidden');
} else {
h.removeClass('is-hidden');
}
}).change()
});

Full-featured autocomplete widget for Dojo

As of now (Dojo 1.9.2) I haven't been able to find a Dojo autocomplete widget that would satisfy all of the following (typical) requirements:
Only executes a query to the server when a predefined number of characters have been entered (without this, big datasets should not be queried)
Does not require a full REST service on the server, only a URL which can be parametrized with a search term and simply returns JSON objects containing an ID and a label to display (so the data-query to the database can be limited just to the required data fields, not loading full data-entities and use only one field thereafter)
Has a configurable time-delay between the key-releases and the start of the server-query (without this excessive number of queries are fired against the server)
Capable of recognizing when there is no need for a new server-query (since the previously executed query is more generic than the current one would be).
Dropdown-stlye (has GUI elements indicating that this is a selector field)
I have created a draft solution (see below), please advise if you have a simpler, better solution to the above requirements with Dojo > 1.9.
The AutoComplete widget as a Dojo AMD module (placed into /gefc/dijit/AutoComplete.js according to AMD rules):
//
// AutoComplete style widget which works together with an ItemFileReadStore
//
// It will re-query the server whenever necessary.
//
define([
"dojo/_base/declare",
"dijit/form/FilteringSelect"
],
function(declare, _FilteringSelect) {
return declare(
[_FilteringSelect], {
// minimum number of input characters to trigger search
minKeyCount: 2,
// the term for which we have queried the server for the last time
lastServerQueryTerm: null,
// The query URL which will be set on the store when a server query
// is needed
queryURL: null,
//------------------------------------------------------------------------
postCreate: function() {
this.inherited(arguments);
// Setting defaults
if (this.searchDelay == null)
this.searchDelay = 500;
if (this.searchAttr == null)
this.searchAttr = "label";
if (this.autoComplete == null)
this.autoComplete = true;
if (this.minKeyCount == null)
this.minKeyCount = 2;
},
escapeRegExp: function (str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
},
replaceAll: function (find, replace, str) {
return str.replace(new RegExp(this.escapeRegExp(find), 'g'), replace);
},
startsWith: function (longStr, shortStr) {
return (longStr.match("^" + shortStr) == shortStr)
},
// override search method, count the input length
_startSearch: function (/*String*/ key) {
// If there is not enough text entered, we won't start querying
if (!key || key.length < this.minKeyCount) {
this.closeDropDown();
return;
}
// Deciding if the server needs to be queried
var serverQueryNeeded = false;
if (this.lastServerQueryTerm == null)
serverQueryNeeded = true;
else if (!this.startsWith(key, this.lastServerQueryTerm)) {
// the key does not start with the server queryterm
serverQueryNeeded = true;
}
if (serverQueryNeeded) {
// Creating a query url templated with the autocomplete term
var url = this.replaceAll('${autoCompleteTerm}', key, this.queryURL);
this.store.url = url
// We need to close the store in order to allow the FilteringSelect
// to re-open it with the new query term
this.store.close();
this.lastServerQueryTerm = key;
}
// Calling the super start search
this.inherited(arguments);
}
}
);
});
Notes:
I included some string functions to make it standalone, these should go to their proper places in your JS library.
The JavaScript embedded into the page which uses teh AutoComplete widget:
require([
"dojo/ready",
"dojo/data/ItemFileReadStore",
"gefc/dijit/AutoComplete",
"dojo/parser"
],
function(ready, ItemFileReadStore, AutoComplete) {
ready(function() {
// The initially displayed data (current value, possibly null)
// This makes it possible that the widget does not fire a query against
// the server immediately after initialization for getting a label for
// its current value
var dt = null;
<g:if test="${tenantInstance.technicalContact != null}">
dt = {identifier:"id", items:[
{id: "${tenantInstance.technicalContact.id}",
label:"${tenantInstance.technicalContact.name}"
}
]};
</g:if>
// If there is no current value, this will have no data
var partnerStore = new ItemFileReadStore(
{ data: dt,
urlPreventCache: true,
clearOnClose: true
}
);
var partnerSelect = new AutoComplete({
id: "technicalContactAC",
name: "technicalContact.id",
value: "${tenantInstance?.technicalContact?.id}",
displayValue: "${tenantInstance?.technicalContact?.name}",
queryURL: '<g:createLink controller="partner"
action="listForAutoComplete"
absolute="true"/>?term=\$\{autoCompleteTerm\}',
store: partnerStore,
searchAttr: "label",
autoComplete: true
},
"technicalContactAC"
);
})
})
Notes:
This is not standalone JavaScript, but generated with Grails on the server side, thus you see <g:if... and other server-side markup in the code). Replace those sections with your own markup.
<g:createLink will result in something like this after server-side page generation: /Limes/partner/listForAutoComplete?term=${autoCompleteTerm}
As of dojo 1.9, I would start by recommending that you replace your ItemFileReadStore by a store from the dojo/store package.
Then, I think dijit/form/FilteringSelect already has the features you need.
Given your requirement to avoid a server round-trip at the initial page startup, I would setup 2 different stores :
a dojo/store/Memory that would handle your initial data.
a dojo/store/JsonRest that queries your controller on subsequent requests.
Then, to avoid querying the server at each keystroke, set the FilteringSelect's intermediateChanges property to false, and implement your logic in the onChange extension point.
For the requirement of triggering the server call after a delay, implement that in the onChange as well. In the following example I did a simple setTimeout, but you should consider writing a better debounce method. See this blog post and the utility functions of dgrid.
I would do this in your GSP page :
require(["dojo/store/Memory", "dojo/store/JsonRest", "dijit/form/FilteringSelect", "dojo/_base/lang"],
function(Memory, JsonRest, FilteringSelect, lang) {
var initialPartnerStore = undefined;
<g:if test="${tenantInstance.technicalContact != null}">
dt = {identifier:"id", items:[
{id: "${tenantInstance.technicalContact.id}",
label:"${tenantInstance.technicalContact.name}"
}
]};
initialPartnerStore = new Memory({
data : dt
});
</g:if>
var partnerStore = new JsonRest({
target : '<g:createLink controller="partner" action="listForAutoComplete" absolute="true"/>',
});
var queryDelay = 500;
var select = new FilteringSelect({
id: "technicalContactAC",
name: "technicalContact.id",
value: "${tenantInstance?.technicalContact?.id}",
displayValue: "${tenantInstance?.technicalContact?.name}",
store: initialPartnerStore ? initialPartnerStore : partnerStore,
query : { term : ${autoCompleteTerm} },
searchAttr: "label",
autoComplete: true,
intermediateChanges : false,
onChange : function(newValue) {
// Change to the JsonRest store to query the server
if (this.store !== partnerStore) {
this.set("store", partnerStore);
}
// Only query after your desired delay
setTimeout(lang.hitch(this, function(){
this.set('query', { term : newValue }
}), queryDelay);
}
}).startup();
});
This code is untested, but you get the idea...

jQuery Datepicker, select multiple dates and mark them via css at selection time, permanently

so I have spent a day developing and reading (teh other way around) to enable my jQuery datepicker to select and highlight mutliple dates.
For this I have managed to write the selected dates to an array which is visualized in a simple textfield.
What I could not manage is to permanently modify the look of the selected date in the datepicker.
I have implemented the "beforeShowDay:" option, which is working properly uppon loading the datepicker, but of course is not called directly on selecting a date.
For this I guessed, I would need to refresh the view "onSelect", but the refresh is not working properly.
Right now, I have some small methods for handling the datearray.
Uppon adding or removing a date, I am trying to refresh the datepicker.
Uppon selecting a date, I am either adding it to, or remove it from the dates-array.
Also, onSelect, I am matching the selected day and try to addClass().
But once again, I think I missed something all the way round, as it is not shown in my datepicker.
Here's my code for now:
var dates = new Array();
function addDate(date) {
if (jQuery.inArray(date, dates) < 0 && date) {
dates.push(date);
}
}
function removeDate(index) {
dates.splice(index, 1);
}
// Adds a date if we don't have it yet, else remove it and update the dates
// textfield
function addOrRemoveDate(date) {
var index = jQuery.inArray(date, dates);
if (index >= 0) {
removeDate(index);
updateDatesField(dates);
} else {
addDate(date);
updateDatesField(dates);
}
jQuery(calContainer).datepicker("refresh");
}
var calContainer = document.getElementById("calendar-container");
jQuery(calContainer).datepicker({
minDate : new Date(),
dateFormat : "#",
onSelect : function(dateText, inst) {
addOrRemoveDate(dateText);
jQuery(".ui-datepicker-calendar tbody tr td a").each(function() {
if (jQuery(this).text() == inst.selectedDay) {
jQuery(this).addClass("ui-state-highlight");
jQuery(this).parent().addClass("selected");
}
});
// addTimeSelectorColumns(dates);
},
beforeShowDay : function(_date) {
var gotDate = -1;
for ( var index = 0; index < dates.length; index++) {
if (_date.getTime() == dates[index]) {
gotDate = 1;
} else {
gotDate = -1;
}
}
if (gotDate >= 0) {
return [ true, "ui-datepicker-today", "Event Name" ];
}
return [ true, "" ];
}
});
function updateDatesField(dates) {
if (dates.length > 0) {
var tmpDatesStrArr = new Array();
var dateString = "";
var datesField = document.getElementById("dates");
for ( var index = 0; index < dates.length; index++) {
var dateNum = dates[index];
var tmpDate = new Date();
tmpDate.setTime(dateNum);
dateString = tmpDate.getDate() + "." + tmpDate.getMonth() + "."
+ tmpDate.getFullYear();
tmpDatesStrArr.push(dateString);
}
jQuery(datesField).val(tmpDatesStrArr);
}
}
(I am still a beginner in Javascript/jQuery, so any help or hints towards my coding are welcome, btw...)
It depends whether you want to stick with jQuery UI or not. If you are open to other library, there is a jQuery Datepicker that supports multiple selection: jquery.datePicker with multiple select enabled. It may save you sometmie fiddling with jQuery UI's one, as it does not natively support multiple selection.
EDIT:
If your main library is not jQuery, I think you should look for a standalone or Prototype-dependent library instead. The JS Calendar looks promising. It natively supports multiple selection by detecting the Ctrl key.

I need to filter the yui datatable which has inline cell editing. and the data is coming from the groovy controller in key:value pair form. as JSON

hi i am also facing the data error problem. i wanted to filter the data coming from json result from the groovy controller in key:value pair. even if i chage the TYPE_JSON to TYPE_JSARRAY,i am getting NoRecordas found in data table but the json result has the data.
please can u correct me.
Thanks in advance!!
dobMenuButton.subscribe("selectedMenuItemChange",function(e) {
var value =e.newValue.value;
if(YAHOO.lang.isValue(value)) {
myDataTable.getDataSource().sendRequest(null, {
success:function(request, response, payload) {
this.initializeTable();
var rs = response.results;
var filtered = [];
for(var i = 0; i < rs.length; i++) {
if(((rs[i].dateOfBirth).format("MM/dd/yyyy")) == value) {
filtered[filtered.length] = rs[i];
}
}
this.getRecordSet().reset();
MCMPagination.paginatorvar.setTotalRecords(filtered.length,true);
this.getRecordSet().setRecords(filtered, 0);
this.render();
},
scope:myDataTable,
argument:myDataTable.getState()
});
}
});

Resources