how to create javascript library for self-written functions - javascript

** want to call common js for all validation for 20 jsp f**
function mAbcRefresher(refresh, refreshTime) {
//function code
}
function QWERTY(address){
//function code
}
function ASDF(address, value, refreshCallback){....
........
........
........`
I just copy these functions to a JS file and include the JS file in my html document. i need some standard way to write this type of validation code

Firstly created that common file eg. common.js. Add it to all your jsp pages. The standered way to write the code in js file
//common.js file
var common={
//function name
formvalidation : function(){
//eg.you want to get all required parts
var elements=$("input:visible, select:visible , textarea:visible");
$.each($(elements) function( index, element ){
//you can get do your code.
$(element).attr("attr");
});
}
//check condition and return false or true
}
above coders for write common functions.
now in jsp to call the function
Add this js file to head
then you can call the function in jsp
like:
$( document ).ready(function() {
//will return true or false
if(common.formvalidation()){
//submit or not
}
});
you can call another function inside this formvalidation() function
just you have assign a variable for this function
var common={
//function name
formvalidation : function(){
var date=this;
var result=date.formDate();
}
formDate : function(){
// do your code
}
}
You can look above code for the idea. definitely it will be helpful for you

Related

from google script to html

I have a function in a .gs file:
function testReturn(){
return "Finaly it works!";
}
and an other in an html file:
<script>
window.addEventListener('load', function() {
google.script.run.withSuccessHandler(createPost).testReturn();
});
/**/
document.getElementById("go_button").addEventListener("click",functionGo);
function functionGo(){
var textToDisplay = google.script.run.testReturn();
document.getElementById("input1_id").value = textToDisplay;
}
</script>
The return is always "undifined". How can I interact between gs and html script? (Of course I don't only want to return an integer, the project is to get a long text wrote with many functions, I'm just looking for a way to get the result and to dispaly it on a html).
Thanks you
You are not implementing the createPost function which is the callback function (because you set it in withSuccessHandler function [1]) that will receive the value returned in your testReturn function from code.gs.
For your html, the code below will update the input value as soon the page is loaded. It should work for you if you have an input element with id set to 'input1_id':
<script>
window.addEventListener('load', function() {
google.script.run.withSuccessHandler(createPost).testReturn();
});
function createPost(returnedValue){
document.getElementById("input1_id").value = returnedValue;
}
</script>
If what you want is to update the input value after a button is clicked, you can use this instead (assuming you have a button with 'go_button' as id):
<script>
document.getElementById("go_button").addEventListener("click",functionGo);
function functionGo(){
google.script.run.withSuccessHandler(createPost).testReturn();
}
function createPost(returnedValue){
document.getElementById("input1_id").value = returnedValue;
}
</script>
Basically, calling an Apps Script function (code.gs) from the html with google.script.run [2] won't directly return you the value, but rather you have to manage the response with a callback function set in one or more of the handler functions [1] (like withSuccessHandler in this example).
[1] https://developers.google.com/apps-script/guides/html/communication#success_handlers
[2] https://developers.google.com/apps-script/guides/html/reference/run

Why a JavaScript function with some specific name is not working while others are?

A very interesting problem I am facing these days is regarding one of my JavaScript function. My JavaScript function with some specific name is not working but if I change its name to anything else then it is working. Have a look -
// function to retain the jquery ui css for toolbar
function retain_css() {
alert('hi');
$( "#new_sort_options" ).buttonset();
}
// new sort
$(document).on("click", ".new_sort_button", function() {
var order = $(this).val();
var make_id = $('#new_make_id').val();
$.ajax({
beforeSend : start_loader(),
type : 'POST',
url : '/ajax/new-sort.php',
data : 'order='+order+'&make_id='+make_id,
dataType : 'json',
success : function(data) {
$("#new_results_toolbar").html(data.toolbar);
$("#new_results").html(data.models);
retain_css();
end_loader();
}
});
});
But retain_css() is not working at all. Even alert() is not firing. But if i change its name to anything such as my_fun() then the code works. I don't understand why it is happening so? Any idea? Don't worry about end_loader() function as it has nothing to deal with my problem. I also changed the order of code when retain_css() was being used but didn't work.
Try not to create global functions because it may collide with other frameworks or libraries.
//define private namespace
window.user3779493Functions = {};
//define method
user3779493Functions.retain_css = function() { ... }
//call method
user3779493Functions.retain_css();
Some functions are already programmed like 'alert('hi');', that is a function called alert:
function alert() {
/* do something */
}
That function also doesn't work.

How Can I Override A Function In Javascript

I have the following scripts:
<script ... jquery-1.9.1.js"></script>
<script ... dataTables.js"></script>
<script ... columnFilter.js"></script>
The following code exists in columnFilter.js:
(function ($) {
$.fn.columnFilter = function (options) {
//some code...
function _fnCreateCheckbox(oTable, aData) {
//some code...
}
};
})(jQuery);
What I would like to do is override function _fnCreateCheckbox(oTable, aData) with my own code. Im fairly new to javascript, so would appreciate an example.
I have tried simply grabbing the code above and adding it to it's own <script> tags, but that didn't work. It completely stopped the columnFilter.js from working (which is as expected I guess). Not really sure what else to try.
function _fnCreateCheckbox(oTable, aData) {
Only exists in the scope in which it was created as (function ($) { creates a function scope. You must edit it there. You can't override it outside the function.
EDIT: On a related note
If you are crafty with JS and you are trying to get that function to do something else only sometimes, you could pass some extra variables into your columnFilter plugin/function call and handle them in that function to do something else. I have no idea what column filter is, but let's pretend to call it on an element like so:
el.columnFilter({optionA: true, optionB: false});
If you wanted to do something else based on some data you have you could do,
el.columnFilter({optionA: true, optionB: false, extraOption: true});
Then in your script, depending on what your entire script does:
$.fn.columnFilter = function (options) {
//some code...
if(options.extraOption){
function _fnCreateCheckbox(oTable, aData) {
//some default code...
}
} else {
function _fnCreateCheckbox(oTable, aData) {
//my other code...
}
}
};
This is a crude example, but just to display your options.
I suppose you import the columnFilter.js file from some external source.
One option could be to copy the columnFilter.js file to your project's directory, modify it as you please and then import it from your project's directory.
You can override a function by reassigning its prototype. It is generally advised against though.
var d = new Date();
alert(d.getFullYear()); // 2013
Date.prototype.getFullYear = function() { return "Full Year"; }
alert(d.getFullYear()); // "Full Year"
http://jsfiddle.net/js5YS/

Organize JS code in MVC app

I have several JS code in several partials Views.
I think it would be good idea to put all these code in separated JS file to separate JS code from HTML code.
But how do you deal with MVC code inside JS?
The example below is JS code which I have in partial View. I would like to put in into JS file but the JS code has MVC code #Url.Action("ResultForm", "File") and it will not be executed in JS file.
Any suggestion?
Javascript Code
<script type="text/javascript">
var varTimerSpeed = 5000;
var varTimerInterval;
var onlyOneInstance = false;
startTimer();
function startTimer() {
onlyOneInstance = false;
varTimerInterval = setInterval(loadResultForm, varTimerSpeed);
}
function loadResultForm() {
if (onlyOneInstance) return;
clearInterval(varTimerInterval);
onlyOneInstance = true;
$.ajax({
url: '#Url.Action("ResultForm", "File")',
data: '',
dataType: 'html',
success: function (data) {
$('#ResultForm').html(data);
startTimer();
}
});
};
</script>
I am assuming using a Razor partial for only the js code is not an option. In that case you could use this approach:
in your view.cshtml
<script type="text/javascript">
var Namespace.urlForModule = '#Url.Action("ResultForm", "File")';
</script>
<script type="text/javascript" src="customScript.js"></script>
in you customScript.js
$.ajax({
url: Namespace.urlForModule,
})
The idea is to separate out the Asp.Net MVC specific code from the js code.
The way you want to do that is upto you. As some one else suggested, you could attach data-* attributes to some div and read those. I prefer this, as it expresses my intent clearly.
A solution would be to create a meta tag or a data-* attribute with the desired dynamic value and catch it with JavaScript. This way you can separate the code entirely with minor changes.
You can add hidden field with url:
// View:
#Html.Hidden("LoadResultFormUrl", #Url.Action("ResultForm", "File"))
// js-file
function loadResultForm() {
url = $("#LoadResultFormUrl").val();
...
};
why dont you just create a partial view which contains nothing but js code
and do a renderpartial instead of adding a script tag?
Create a file "somescript.js" and put the code inside a unique public function, extract hard-coded external dependencies and replace them for parameters.
var startXyz = function(resultFormUrl) {
var varTimerSpeed = 5000;
var varTimerInterval;
var onlyOneInstance = false;
startTimer();
function startTimer() {
onlyOneInstance = false;
varTimerInterval = setInterval(loadResultForm, varTimerSpeed);
}
function loadResultForm() {
if (onlyOneInstance) return;
clearInterval(varTimerInterval);
onlyOneInstance = true;
$.ajax({
url: resultFromUrl,
data: '',
dataType: 'html',
success: function (data) {
$('#ResultForm').html(data);
startTimer();
}
});
};
};
Then, in your page you do:
<script>
$(function(){
startXyz('#Url.Action("ResultForm", "File")');
});
</script>
Now you have a modular function that will startup your page/partial and a script file that do not depends directly from server state and can be reused on the same or another page.
This approach is especially useful if a partial view is rendered more than once per page.

JQuery can't find variable from separate javascript file

I am using the cakephp framework and I created 2 separate javascript files and placed them into my webroot/js folder. The first javascript file contains modal dialog variables that contain the settings for the dialog boxes. The second javascript file contains other click event handlers that post data to an action and then open up the dialog.
The problem I am having is that the second file calls a variable from the first file using
$variablename and I get an error saying varaibleName is not defined.
Some code is below to show you what I mean.
From the first file:
var $editSel = $("#editSel_dialog").dialog(
{
autoOpen: false,
height: 530,
width: 800,
resizable: true,
modal: true,
buttons:
{
"Cancel": function()
{
$(this).dialog("close");
}
}
});
From the second file:
$('.neweditSel_dialog').live('click', function()
{
$.ajaxSetup({ async: false });
var selected = [];
$("#[id*=LocalClocks]").each(function()
{
if(false != $(this).is(':checked'))
{
var string = $(this).attr('id').replace('LocalClocks', '');
string = string.substring(10);
selected.push(string);
}
});
if(0 === selected.length)
{
$selError.dialog('open');
$selError.text('No Local Clocks Were Selected')
}
else
{
$.post('/LocalClocks/editSelected', { "data[Session][selected]": selected }, function(data)
{
});
$editSel.load($(this).attr('href'), function ()
{
$editSel.dialog('open');
});
}
return false;
});
This was working when I was using jquery-1.4.2.min.js, but I am using jquery1.7 now.
I also ended up putting the first file with all the variables inside of $(document).ready(function(){}); I tried putting the second file inside of a document.ready() function but that made no difference.
Any help would be great.
Thanks
You are dealing with an issue in scope. In javascript:
function foo() {
var greet = "hi";
}
function bar() {
console.log(greet); // will throw error
}
However:
var greet;
function foo() {
greet = "hi";
}
function bar() {
console.log(greet); // will log "hi"
}
You must define your variable in a common parent of both functions that need to access it. Unfortunately, since you do not use any modeling convention or framework, that is the window object (why are global variables bad?).
So, you must define var $whateveryouneed before and outside of both $(document).readys.
Also, keep the declaration and definition seperate. Your definition instantiates a jQuery object, so you must encapsulate it inside a $(document).ready() (use $(function() {}) instead):
var $editSel;
$(function () {
$editSel = $("#editSel_dialog").dialog(
{
autoOpen: false,
height: 530,
width: 800,
resizable: true,
modal: true,
buttons:
{
"Cancel": function()
{
$(this).dialog("close");
}
}
});
});
I don't think you can guarantee the order in which handlers will be fired, which means that the document ready may be fired in different order than you expect. Is the variable you are trying to access in the second file a global variable? Try to think about your variables scope as I would have thought this is the issue.
You cannot guarantee that one file will be loaded before the other. And you cannot guarantee that document.ready in one file will fire before the other.
Therefore, I suggest you wrap your code in functions and call them in a single document.ready handler in the order you need.
For example:
function initVariables(){
window.$editSel = ... // your code from the first file here
}
function initHandlers(){
// your code from the second file here
}
And then:
$(document).ready(function() {
initVariables();
initHandlers();
});
You'll notice that I used the global window object to expose your variable. It would be even better if you used a common namespace for them.

Categories