I am learning how to write a jQuery plugin. I have this code below, my question is what does this stand for in the code below?
$.fn.myNewPlugin = function() {
return this.each(function() {
// Do something to each element here.
});
};
When you write a plugin you are extending the jQuery object, and because the jQuery object is a sequence, when you use return this.each(function () { }); then your plugin is executed for each item of the sequence.
Related
In our application we have more than 100 grids and we need to display help button on Title bar of grid, for that I have created a plugin using
$.jgrid.extend({
EnableHelpButton: function(value) {
var $t = this;
...............;
}
});
Currently, I go to each .html page of grid and need to call the EnableHelpButton as shown in below code.
-----------------Index1.html-------------------------
$("#TestGrid1").bind("jqGridInitGrid", function () {
$(this).EnableHelpButton(true);
});
-----------------Index2.html-------------------------
$("#TestGrid2").bind("jqGridInitGrid", function () {
$(this).EnableHelpButton(true);
});
How I can create a generic way to call this EnableHelpButton on jqGridInitGrid events of each grid. It should write once on single place and it should work for each grid.
You have to have some specific call of your custom function on every page. One way will be to define you plugin so
$.jgrid.extend({
EnableHelpButton: function(value) {
var $t = this;
...............;
},
myInit: function () {
return this.each(function () {
$(this).bind("jqGridInitGrid", function ({
$(this).EnableHelpButton(true);
});
});
}
});
Even in the case you need to include .jqGrid("myInit") call on every page. You can make the call of myInit before the <table> is converted to grid. For example instead of
$("#grid").jqGrid({
... // parameter used to create jqGrid
});
you will be use now
$("#grid").jqGrid("myInit").jqGrid({
... // parameter used to create jqGrid
});
Only if you never use onInitGrid callback in any your grids you can use the callback instead of jqGridInitGrid. In the case you need just define the callback in some JavaScript code which you included in every your page:
$.extend(true, $.jgrid.defaults, {
onInitGrid: function () {
$(this).EnableHelpButton(true);
}
});
In the way you will set default implementation of onInitGrid for every grid.
Thus the definition of common initialization inside of onInitGrid callback produces the shortest implementation, but have restriction that you shouldn't use the callback in no of your grids. Alternatively you defines the method myInit which makes all bindings add you can add .jqGrid("myInit") on every your grids. The last approach will work for every jqGrid.
I'm trying to get the hang of using ajax loads (mostly via jquery) to make my site more efficient. Wondering if anyone can provide any suggestions re "best practices" for using ajax?
Is there a way to simplify a script for multiple ajax calls? For example, I currently have the working script:
$(document).ready(function() {
$('#dog').click(function () {
$('#body').load("dog.html");
});
$('#cat').click(function () {
$('#body').load("cat.html");
});
$('#bird').click(function () {
$('#body').load("bird.html");
});
$('#lizard').click(function () {
$('#body').load("lizard.html");
});
});
The script just gets longer and longer with each additional function. Is there a simpler, more efficient way to write this script to cover multiple load scripts?
Also, should I be using ajax loads to replace the majority of actual links?
Here is a suggestion, since the code you posted seems to have a pattern between the id and the filename:
$(document).ready(function () {
$(document).on('click', 'commonParentElementHere', function (e) {
$('#body').load(e.target.id + ".html");
});
});
This suggestion uses .on() and you just need to add a commonParentElementHere, a id or a class of the common parent of those elements.
Another option is to use a class on all elements that should be clickable, and then use the code passing the id to the html file name, like:
$(document).ready(function () {
$(document).on('click', '.theCOmmonClass', function () {
$('#body').load(this.id + ".html");
});
});
I'd say give all the elements you want to click on a class say ajax then.
$(document).ready(function() {
$('.ajax').click(function () {
$('#body').load(this.id + ".html");
});
});
Assuming that the id matches the file name the script can be simplified to:
$(document).ready(function() {
$('#dog,#cat,#bird,#lizard').click(function () {
var fileName = this.id + ".html";
$('#body').load(fileName);
});
});
This script simply specifies each id in a single selector that separates each id with a comma. This will calls the click function to be fired for each element. With the anonymous function attached to the click event, the id of each element is obtained and concatenated to create the file name which is then passed to the load function.
If the id doesn't always match the element you could use the following approach.
var mappings = [
{id: "fileName1", file:"file.html"},
{id: "fileName2", file:"file2.html"}
];
$(document).ready(function() {
for(var i = 0; i < mappings; i++){
createMapping(mappings[i]);
}
function createMapping(mapping){
$("#" + mapping.id).click(function(){
$('#body').load(mapping.file);
});
}
});
$('.collapse').each(function() {
var title= $(this).siblings('.accordion-heading').find('a');
$(this).on('show hide', function (e) {
if(!$(this).is(e.target))return;
title.parent().toggleClass('active', 300);
title.parent().hasClass('active') ? $('input.party').prop('value', '') : $('input.party').val(title.siblings('.delete').prop('id'));
var id = title.siblings('.delete').prop('id');
var data = {id: id};
$.post("times.php", data, function(result) {
if(title.parent().hasClass('active')){
$('.times').html('');
} else {
$('.times').html($.parseJSON(result));
}
})
})
})
So I am adding a new accordion-group to my html by adding a new party and I wan't all this to work on the newly added elements as well. I didn't find topics that could help me since it is a bit more specific than any random each function (I think).
This future elements thing is new to me, so I would appreciate some explanations or a good link to a place other that the jquery website which I already checked.
Thank you for your time!
Basically what I want to do this replace $(this).on('show hide', function (e) { with something like $(document).on('show hide', $(this), function (e) {. What I just wrote doesn't work though.
If it is just about the event handler, then you can use event delegation to capture the event on dynamically created elements as well.
There is not reason why you have to use .each here, so just omit it:
$(document.body).on('show hide', '.collapse', function() {
var title = $(this).siblings('.accordion-heading').find('a');
if(!$(this).is(e.target))return;
// rest of the code...
});
this will apply on any new objects matching selector
jQuery(document).on('show hide', '.accordion-heading a', function(event){
...
});
I recently had a question on getting checkbox validation working on the client side within a MVC project. This question was successfully answered, but raised another query.
In order for my checkbox validation to work I needed to add the following bits of javascript directly into jquery.validate.unobtrusive.js:
$jQval.addMethod("mustbetrue", function (value, element, param) {
// check if dependency is met
if (!this.depend(param, element))
return "dependency-mismatch";
return element.checked;
});
adapters.add("mustbetrue", function (options) {
setValidationValues(options, "mustbetrue", true);
});
this worked great, but I'm unhappy about having to change this file just in case Microsoft or the validation plugin boys update the file in the future. If I'm not still working on the project this file may be overwritten without people realising it's been customised.
So with that in mind I tried adding this into an external javascript file:
$.validator.addMethod("mustbetrue", function (value, element, param) {
// check if dependency is met
if (!this.depend(param, element))
return "dependency-mismatch";
return element.checked;
});
$.validator.unobtrusive.adapters.add("mustbetrue", function (options) {
setValidationValues(options, "mustbetrue", true);
});
Unfortunately now the client side script on my checkboxes doesn't run. Can anyone see what I'm doing wrong?
Thanks in advance
S
Sniffer,
The more I look at this, the more I shake my head (at myself).
Upon further review, Darin's method will work, provided that you add one line to his page script:
<script type="text/javascript">
$.validator.unobtrusive.adapters.addBool("mustbetrue", "required");
$.validator.unobtrusive.parse();
</script>
Whenever you make a change (such as adding a new adapter), you must re-parse the unobtrusive validation attributes. Since the last action in jquery.validate.unobtrusive.js is the parsing of the attributes, and the adapter is being added after the parsing, re-parsing solves this issue.
counsellorben
P.S. This solves your issue, but still leaves unresolved the issue of how to add other custom validators which do not use built-in methods from jquery.validate.js without modifying jquery.validate.unobtrusive.js.
P.P.S. I found the answer for adding custom validation methods. In order to add custom validation mmethods without modifying jquery.validate.unobtrusive.js, you need to "borrow" some of its code to add to your page script. Adding a custom method then looks like the following:
<script type="text/javascript">
var $jQval = $.validator,
adapters,
data_validation = "unobtrusiveValidation";
function setValidationValues(options, ruleName, value) {
options.rules[ruleName] = value;
if (options.message) {
options.messages[ruleName] = options.message;
}
}
$jQval.addMethod("mustbetrue", function (value, element, param) {
// check if dependency is met
if (!this.depend(param, element))
return "dependency-mismatch";
return element.checked;
});
$.validator.unobtrusive.adapters.add("mustbetrue", function (options) {
setValidationValues(options, "mustbetrue", true);
});
$jQval.unobtrusive.parse();
</script>
Unobtrusive validation is giving me nothing but grief.
In a very very simple test page, this works:
$(document).ready(function () {
jQuery.validator.unobtrusive.adapters.add(
'mustbetrue', ['properties'], function (options) {
options.rules['mustbetrue'] = options.params;
options.messages['mustbetrue'] = options.message;
}
);
jQuery.validator.addMethod('mustbetrue', function (value, element, params) {
// check if dependency is met
if (!this.depend(param, element)) {
return "dependency-mismatch";
}
switch (element.type) {
case "checkbox":
return element.checked;
break;
case "hidden":
return (value == 'true' || value == 'True');
break;
default:
alert('type = ' + element.type);
return true;
break;
}
});
});
However, when I move this code to my more complex form, suddenly it stops working and I have no idea why and no time to delve into the unobtrusive code to try and find out.
counsellorben's solution works in my more complex form.
If anyone can point me to a site that explains in detail how to properly add a custom validator to unobtrusive validation, I will be forever greatful. Each site I visit has a different solution.
I have no problem adding this code to an external javascript file, which i pilfered from This site
// Custom validator for checkboxs
jQuery.validator.unobtrusive.adapters.add("brequired", function (options) {
//bool-required for checkboxes
if (options.element.tagName.toUpperCase() == "INPUT" &&
options.element.type.toUpperCase() == "CHECKBOX")
{
options.rules["required"] = true;
if (options.message) {
options.messages["required"] = options.message;
}
}
});
Are you certain that you put your script AFTER the jquery scripts in your page? Mine is the last in the list.
Why are none of the live (or dead) events I bind to a dynamic element firing?
(function ($) {
$.fn.myPlugin = function () {
var $filterBox = $("<input type='text'>").live("click", function () {
alert("Clicked");
});
this.before($filterBox); // insert into DOM before current element
return this; // keep chain
};
})(jQuery);
I am calling myPlugin on several <select> elements. I thought it would work without the Live plugin if I bound it before adding the element to the DOM, but not even the live events are firing. Is it because my element has no ID?
Edit:
The following does not work either:
var $filterBox = $("<input type='text'>").bind("click", function () {
alert("Clicked");
});
.live() works off a selector (since it checks the target against the selector at the time the event happens), you can't attach it directly to an element...you should just use .click() in these cases:
(function ($) {
$.fn.myPlugin = function () {
var $filterBox = $("<input type='text'>").click(function () {
alert("Clicked");
});
this.before($filterBox); // insert into DOM before current element
return this; // keep chain
};
})(jQuery);
You can try it out here, or a bit shorter with .insertBefore():
(function ($) {
$.fn.myPlugin = function () {
$("<input type='text'>").click(function () {
alert("Clicked");
}).insertBefore(this);
return this;
};
})(jQuery);
You can test it here.
The live method works with selectors, not detached elements.
You can handle the normal (non-live) click event, and it should work fine.
Why not just bind it? http://jsfiddle.net/9WvpA/
Can it be just because "<input type='text'>" is not a valid HTML? You have not closed your tag. However, I am not sure whether jQuery is unable to close it for you.
Solved by not using global variables that replaced each other, and iterating over each element in question with this.each(...):
(function ($) {
$.fn.myPlugin = function () {
return this.each(function () {
// do stuff
});
};
})(jQuery);