JavaScript trigger does not work - javascript

I try to trigger a button so when user loads a page, the button is automatically clicked.
My code is following:
$(document).ready(function() {
console.log("it's here");
$("#btnPeriod").trigger('click');
});
$("#btnPeriod").on('click', function(){
var ahhhhh = "<security:authentication property="securityUser.fullName"/>";
ahhhhh = ahhhhh.replace(/ /g, " ");
console.log(ahhhhh);
$.extend($("#noticeList").jqGrid("getGridParam", "postData"),{
filters : JSON.stringify({
groupOp : "OR",
rules : [{
field : "notiWriter",
op : "eq",
data : ahhhhh
}],
groups : []
})
});
$("#noticeList").jqGrid("setGridParam", {search : true}).trigger('reloadGrid', [{current : true, page : 1}]);
});
and when the page is loaded, I can see log of "it's here" and value of ahhhhh. However, even though I can see log, the action suppose to be happened does not get applied. Funny thing is when I click the button, then it works, with another log message of variable ahhhhh.
FYI, I am using jqGrid and when I click btnPeriod button, it filters rows that its cellvalue of notiWriter does not match with variable ahhhhh.
For now, when I load this page, it displays like following:
And then, when I click a button, it only shows certain rows like following:
And I hope it always look like second picture when a user loads the page.
I once used setTimeout, but it turned out it did not work well, so I hope you give me some help.
Thank you in advance.

You need to bind the click handler to the button inside the document.ready handler, and before you call trigger(). Try this:
$(document).ready(function() {
$("#btnPeriod").on('click', function(){
var ahhhhh = "<security:authentication property="securityUser.fullName"/>";
ahhhhh = ahhhhh.replace(/ /g, " ");
console.log(ahhhhh);
$.extend($("#noticeList").jqGrid("getGridParam", "postData"),{
filters : JSON.stringify({
groupOp : "OR",
rules : [{
field : "notiWriter",
op : "eq",
data : ahhhhh
}],
groups : []
})
});
$("#noticeList").jqGrid("setGridParam", {
search: true
}).trigger('reloadGrid', [{
current: true,
page: 1
}]);
});
$("#btnPeriod").trigger('click');
});

Try including the event binding inside the jquery ready function and bind the event before trigger the click:
$(document).ready(function() {
console.log("it's here");
$("#btnPeriod").on('click', function(){
var ahhhhh = "<security:authentication property="securityUser.fullName"/>";
ahhhhh = ahhhhh.replace(/ /g, " ");
console.log(ahhhhh);
$.extend($("#noticeList").jqGrid("getGridParam", "postData"),{
filters : JSON.stringify({
groupOp : "OR",
rules : [{
field : "notiWriter",
op : "eq",
data : ahhhhh
}],
groups : []
})
});
$("#noticeList").jqGrid("setGridParam", {search : true}).trigger('reloadGrid', [{current : true, page : 1}]);
});
$("#btnPeriod").trigger('click');
});

Why not including the click event binding inside your ready function ?
$(document).ready(function() {
console.log("it's here");
$("#btnPeriod").on('click', function() {
var ahhhhh = "<security:authentication property="securityUser.fullName"/>";
ahhhhh = ahhhhh.replace(/ /g, " ");
console.log(ahhhhh);
$.extend($("#noticeList").jqGrid("getGridParam", "postData"), {
filters : JSON.stringify({
groupOp : "OR",
rules : [{
field : "notiWriter",
op : "eq",
data : ahhhhh
}],
groups : []
})
});
$("#noticeList").jqGrid("setGridParam", {search : true}).trigger('reloadGrid', [{current : true, page : 1}]);
});
$("#btnPeriod").trigger('click');
});

Related

Change the way a collection is sorted through the client

I have a collection that is shown on a page :
Template.body.helpers({
chansonsFutures(){
return Chansons.find({
"playedStatus":false
},{
sort : { score:-1 }
});
},
});
And I would like the user to be able to change the way the collection is sorted. In the example it is sorted by score, but how would I go about sorted by something else?
I have a select in place :
<select id="ordre">
<option value="shuffle">Aléatoire</option>
<option value="vote">Vote</option>
<option value="lastAdded">Dernier Ajout</option>
</select>
But if I put an if condition in Template.body.helpers, meteor tells my application has errors and is waiting for file changes. If I put the condition in Template.body.events and link it to the change of my select, it also gives me errors.
How should I proceed?
edit : to answer #Justinas, here is how I put the condition in code.
My first try was straight in the helper :
Template.body.helpers({
if(document.getElementById("ordre").value == "lastAdded"){
chansonsFutures(){
return Chansons.find({
"playedStatus":false
},{
sort : { lastAdded:-1 }
});
},
};
else if (other value for the select) {
other stuff happens
};
});
And the other way was like this :
Template.body.events({
'change #ordre'(event){
event.preventDefault();
chansonsFutures(){
return Chansons.find({
"playedStatus":false
},{
sort : { document.getElementById("ordre").value:-1 }
});
},
},
});
Here it is what you need to add in your js fiile :
By defalult it will sot by 'score' and on changing select value it will change accordingly.
Template.body.onCreated(function() {
this.sortBy = new ReactiveVar('score');
})
Template.body.helpers({
chansonsFutures : function(){
var sortParam = Template.instance().sortBy.get();
return Chansons.find({
"playedStatus":false
},{
sort : { sortParam:-1 }
});
},
});
Template.body.events({
'change #ordre':function (event,templateInstance) {
var sortSelected = $('#ordre option:selelcted').val();
templateInstance.sortBy.set(sortSelected)
}
})

How to include HTML code within prime ui or jquery datatable "columns" option's headerText?

I am trying to apply internationalization to my web app that uses JSP pages.I found this link How to internationalize a Java web application? and it really helped me.
However I am now trying to use the given tag fmt:message tag within my primeui datatable's headerText so that I can see column name of my datatable in spanish language.But it's being displayed as text on the screen.Whereas I want it to function as it does on my JSP page i.e to pick user.data.userName="spanish translation for username" from my properties file text_es.properties.
Below is the code for my datatable which is included in script tag on my JSP:
$(function() {
$('#tbllocal').puidatatable({
caption : 'Inbox Tasks',
paginator : {
rows : 5
},
columns : [
{
field : 'userName',
**headerText : '<fmt:message key='user.data.userName'/>',**
sortable : true
},{
field : 'userEmailId',
headerText : 'userEmailId',
sortable : true
} ],
datasource : function(callback) {
$.ajax({
type : "GET",
url : 'crud',
dataType : "json",
context : this,
success : function(response) {
callback.call(this, response);
}
});
},
selectionMode : 'single',
rowSelect : function(event, data) {
$('#messages').puigrowl('show', [ {
severity : 'info',
summary : 'Row Selected',
detail : (data.firstName + ': ' + data.lastName)
} ]);
},
rowUnselect : function(event, data) {
$('#messages').puigrowl('show', [ {
severity : 'info',
summary : 'Row Unselected',
detail : (data.firstName + ': ' + data.lastName)
} ]);
},
jsonReader : {
response : "response"
}
});
});
Still there is no support for including html in datatable header till primeui 2.0 i have also posted this question on frimeui forum please refer following link for further details
http://forum.primefaces.org/viewtopic.php?f=16&t=42417

how to access function in Json

I am able to access the onclick properties function for the printButton property at the end of the block. Although I am unable to initiate the onclick functions under the exportButton property.I have the following code.
B.exporting = {
type : "image/png",
url : "http://export.highcharts.com/",
width : 800,
enableImages : false,
buttons : {
exportButton : {
symbol : "exportIcon",
x : -10,
symbolFill : "#A8BF77",
hoverSymbolFill : "#768F3E",
_titleKey : "exportButtonTitle",
menuItems : [{
textKey : "downloadPNG",
onclick : function() {
this.exportChart()
}
}, {
textKey : "downloadJPEG",
**onclick : function() {
this.exportChart({
type : "image/jpeg"
})**
}
}, {
textKey : "downloadPDF",
onclick : function() {
this.exportChart({
type : "application/pdf"
})
}
}, {
textKey : "downloadSVG",
onclick : function() {
this.exportChart({
type : "image/svg+xml"
})
}
}
}]
},
printButton : {
symbol : "printIcon",
x : -36,
symbolFill : "#B5C9DF",
hoverSymbolFill : "#779ABF",
_titleKey : "printButtonTitle",
onclick : function() {
this.print()
}
}
}
};
I am binding keyboard controls to the click events using the jquery plugin this is what I used to print. This Works!:
Mousetrap.bind('ctrl+s', function(e) { B.exporting.buttons.printButton.onclick(this.print());
});
This code is what I tried to access an individual onclick function under the exportButton property in the json above
Mousetrap.bind('*', function(e) {B.exporting.buttons.exportButton.menuItems[0].onclick;});
The result i get is the value but i want to run the function as the onclick property does.Does anyone know how to run a function under a json property?I Appreciate any help here thanks folks.
Mousetrap.bind('click', B.exporting.buttons.exportButton.menuItems[0].onclick);
Your ctrl-s binding also looks wrong, it should be:
Mousetrap.bind('ctrl+s', B.exporting.buttons.printButton.onclick);
The printButton.onclick function doesn't take an argument. Your binding calls this.print before calling the printButton.onclick function, and then the printButton.onclick function
does it again.

Need to retain dynamically created option in combo box using Knockout.js

I have a codeset that dynamically creates an "option" in a select box. But, since we're using Knockout, when I go to SELECT that newly created option, and click on it, it gets removed, e.g. DISAPPEARS! Poof!!!!
So, here's the create script:
function createNewGroup()
{
var htmlSelect = document.getElementById('groups');
var optionValue = document.getElementById('newgroupname');
if (optionValue.value === '')
{
alert('Please enter group name.');
optionValue.focus();
return false;
}
if (isOptionAlreadyExist(htmlSelect, optionValue.value))
{
optionValue.value = "";
alert('Group name already exists.\n\nPlease try again.');
optionValue.focus();
return false;
}
var selectBoxOption = document.createElement("option");
selectBoxOption.value = optionValue.value;
selectBoxOption.text = optionValue.value;
htmlSelect.add(selectBoxOption, null);
optionValue.value = "";
alert("New group has been added successfully.");
optionValue.focus();
return true;
};
Since this is a KNOCKOUT observable, how to keep it in the box when I select it, moreover, how do I send that new value back to JSON object. Here's an example of that:
{"groups":[
{
"groupname" : "Administrator",
"attr" : { "id" : "li.attr.node_1",
"href" : "#",
"data-bind" : "click: grpMgmt('Administrator');" }
},
{
"groupname" : "Guest",
"attr" : { "id" : "li.attr.node_2",
"href" : "#",
"data-bind" : "click: grpMgmt('Guest');" }
}
]
}
Hence, the admin user can create a new user so it can look like this:
{"groups":[
{
"groupname" : "Administrator",
"attr" : { "id" : "li.attr.node_1",
"href" : "#",
"data-bind" : "click: grpMgmt('Administrator');" }
},
{
"groupname" : "Guest",
"attr" : { "id" : "li.attr.node_2",
"href" : "#",
"data-bind" : "click: grpMgmt('Guest');" }
}
],
"users":[
{
"groupname" : "Joes Users",
"attr" : { "id" : "li.attr.node_1",
"href" : "#",
"data-bind" : "click: grpMgmt('Joe');" }
}
]
}
OK, I'll stop writing for now... thanks...
If you're using knockout (which I can't actually see) all you need to do is bind your select box to an observable array and when you need to add a new item just push it onto the array and knockout will add it to the list for you.
Knockout should essentially replace that script you've included with a lot less, much more simplistic code.

Performance issue with JSON and auto Complete [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I am trying to write an app that will work online and offline using technologies such as application cache and local storage. I am using jQuery mobile and an jqm autocomplete solution which can be found here http://andymatthews.net/code/autocomplete/
The idea is that if the app is on-line then I will be calling a remotely accessible function via ajax which will set data. The ajax calls that are made bring back data for events, countries and hospitals. Once the data as been returned I am setting the data in localStorage.
If the data already exists in localStorage then I can continue while being offline as I don't have to rely on the ajax calls.
I am having performance issues with this code when running on iPad/mobile devices. Where the hospital data is concerned. There is a large amount of data being returned for hospitals, please see sample of JSON for hospital data below. It can be a little slow on desktop but not nearly as bad.
Can anyone see any improvements to the code I have below to increase the performance.
JSON hospital data example
{ "hospitals" : {
"1" : { "country" : "AD",
"label" : "CAIXA ANDORRANA SEGURETAT SOCIAL"
},
"10" : { "country" : "AE",
"label" : "Advance Intl Pharmaceuticals"
},
"100" : { "country" : "AT",
"label" : "BIO-KLIMA"
},
"1000" : { "country" : "BE",
"label" : "Seulin Nicolas SPRL"
},
"10000" : { "country" : "ES",
"label" : "Dental 3"
},
"10001" : { "country" : "ES",
"label" : "PROTESIS DENTAL MACHUCA PULIDO"
},
"10002" : { "country" : "ES",
"label" : "JUST IMPLANTS, S.L."
},
"10003" : { "country" : "ES",
"label" : "CTRO DENTAL AGRIC ONUBENSE DR.DAMIA"
},
"10004" : { "country" : "ES",
"label" : "HTAL. VIRGEN DE ALTAGRACIA"
},
"10005" : { "country" : "ES",
"label" : "HOSPITAL INFANTA CRISTINA"
}....
/*global document,localStorage,alert,navigator: false, console: false, $: false */
$(document).ready(function () {
//ECMAScript 5 - It catches some common coding bloopers, throwing exceptions. http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
//It prevents, or throws errors, when relatively "unsafe" actions are taken (such as gaining access to the global object).
//It prevents, or throws errors, when relatively "unsafe" actions are taken (such as gaining access to the global object).
"use strict";
//initialise online/offline workflow variables
var continueWorkingOnline, continueWorkingOffline, availableEvents, availableHospitals, availableCountries, availableCities;
continueWorkingOnline = navigator.onLine;
var getLocalItems = function () {
var localItems = [];
availableEvents = localStorage.getItem('eventData');
availableHospitals = localStorage.getItem('hospitalData');
availableCountries = localStorage.getItem('countryData');
if (availableEvents) {
//only create the array if availableEvents exists
localItems[0] = [];
localItems[0].push(availableEvents);
}
if (availableCountries) {
//only create the array if availableCountries exists
localItems[1] = [];
localItems[1].push(availableCountries);
}
if (availableHospitals) {
//only create the array if availableHospitals exists
localItems[2] = [];
localItems[2].push(availableHospitals);
}
if (availableCities) {
//only create the array if availableHospitals exists
localItems[3] = [];
localItems[3].push(availableCities);
}
return localItems;
};
//Check to see if there are 3 local items. Events, Countries, Cities. If true we know we can still run page off line
continueWorkingOffline = getLocalItems().length === 3 ? true: false;
//Does what is says on the tin
var populateEventsDropDown = function (data) {
var eventsDropDown = $('#eventSelection');
var item = data.events;
$.each(item, function (i) {
eventsDropDown.append($('<option></option>').val(item[i].id).html(item[i].name));
});
};
//Called once getData's success call back is fired
var setFormData = function setData(data, storageName) {
//localStorage.setItem(storageName, data);
localStorage.setItem(storageName, data);
};
//This function is only called if continueWorkingOnline === true
var getRemoteFormData = function getData(ajaxURL, storageName) {
$.ajax({
url: ajaxURL,
type: "POST",
data: '',
success: function (data) {
setFormData(data, storageName);
}
});
};
//Function for autoComplete on Hospital data
var autoCompleteDataHospitals = function (sourceData) {
var domID = '#hospitalSearchField';
var country = $('#hiddenCountryID').val();
var items = $.map(sourceData, function (obj) {
if (obj.country === country) {
return obj;
}
});
$(domID).autocomplete({
target: $('#hospitalSuggestions'),
source: items,
callback: function (e) {
var $a = $(e.currentTarget);
$(domID).val($a.data('autocomplete').label);
$(domID).autocomplete('clear');
}
});
};
//Function for autoComplete on Country data
var autoCompleteDataCountries = function (sourceData) {
var domID = '#countrySearchField';
var domHiddenID = '#hiddenCountryID';
var items = $.map(sourceData, function (obj) {
return obj;
});
$(domID).autocomplete({
target: $('#countrySuggestions'),
source: items,
callback: function (e) {
var $a = $(e.currentTarget);
$(domID).val($a.data('autocomplete').label);
$(domID).autocomplete('clear');
$(domHiddenID).val($a.data('autocomplete').value);
//enable field to enter Hospital
$('#hospitalSearchField').textinput('enable');
//Call to autoComplete function for Hospitals
autoCompleteDataHospitals(availableHospitals.hospitals);
}
});
};
if (continueWorkingOnline === false && continueWorkingOffline === false) {
alert("For best results this form should be initiated online. You can still use this but auto complete features will be disabled");
}
if (continueWorkingOnline === true && continueWorkingOffline === false) {
getRemoteFormData('templates/cfc/Events.cfc?method=getEventsArray', 'eventData');
getRemoteFormData('templates/cfc/Countries.cfc?method=getCountriesArray', 'countryData');
getRemoteFormData('templates/cfc/Hospitals.cfc?method=getHospitalsArray', 'hospitalData');
$(document).ajaxStop(function () {
//set the variables once localStorage has been set
availableEvents = JSON.parse(localStorage.getItem("eventData"));
availableHospitals = JSON.parse(localStorage.getItem('hospitalData'));
availableCountries = JSON.parse(localStorage.getItem('countryData'));
//Inserts data into the events drop down
populateEventsDropDown(availableEvents);
autoCompleteDataCountries(availableCountries.countries);
});
}
if (continueWorkingOnline === true && continueWorkingOffline === true) {
//get the localStorage which we know exists because of continueWorkingOffline is true
availableEvents = JSON.parse(localStorage.getItem('eventData'));
availableHospitals = JSON.parse(localStorage.getItem('hospitalData'));
availableCountries = JSON.parse(localStorage.getItem('countryData'));
//Inserts data into the events drop down
populateEventsDropDown(availableEvents);
autoCompleteDataCountries(availableCountries.countries);
}
});
If your bottleneck is downloading that massive json file, the only way to make it less of a bottleneck is to make it smaller or to send less data. For example, you could sort your hospitals by country and store arrays rather than objects with keys to make the json smaller rather than repeating keys over and over.
{
"AD":[
"CAIXA ANDORRANA SEGURETAT SOCIAL"
],
"AE":[
"Advance Intl Pharmaceuticals"
],
...
"ES":[
"Dental 3",
"Dental 4",
"Dental 5"
]
}
if the id field is important, use
...
"ES":[
["10000","Dental 3"],
["10001","Dental 4"],
["10002","Dental 5"]
]
You would of course need to update the rest of your code to use this json format rather than your previous.

Categories

Resources