dynamically extend jQuery plugin - javascript

i want to create a flexible jquery plugin for handling forms, here's my markup + code:
<div id="myform" validate="1">form</div>
<script>
(function ($) {
$.fn.myForm = function()
{
var me = this;
if(me.attr("validate"))
{
me.validate();
}
};
})(jQuery);
// code from external file eg. myform_validate.js
$.fn.myplugin.validate = function () {
// form validation here
alert("validate");
};
$(document).ready(function(){
$('#myform').myForm();
});
</script>
what i want to achieve is somekind of plugin-in-plugin structure which means myForm is the base plugin for each project and if required i would add extra functionality/methods like form validation or an image uploader to the plugin (by loading additional external scripts).
this should be dont without instantiation, directly inside the plugin.
as you might expect, the above code doesn't work .. :/
any ideas if this is possible?
thanks

There are probably numerous ways to achieve expected results. Here, checks if validate method from "external file" is defined, if yes, sets validate as property of myForm ; utilizes Function.prototype.call to set this within validate
(function($) {
function myForm() {
me = this;
if (me.attr("validate")) {
if (myForm.validate) {
myForm.validate.call(me)
.text(me.text() + " validated")
.css("color", "green");
}
};
return me
};
try {
if (validate && typeof validate === "function") {
myForm.validate = validate
}
// catch `ReferenceError` if `validate` is not defined
} catch (e) {
alert(e.message)
}
$.fn.myForm = myForm;
})(jQuery);
// code from external file eg. myform_validate.js
$(document).ready(function() {
$("#myform").myForm();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>
// external file
function validates() {
// form validation here
console.log(this)
alert("validate");
// `this` : `#myform`
return this
};
</script>
<div id="myform" validate="1">form</div>

Related

Button dont work after adding a pop up javascript

So I have a button on my HTML code that I have set to hide a certain content. However; when I added a popup feature to my code it makes the button not work.
JS for the popup:
$ = function(id) {
return document.getElementById(id);
}
var show = function(id) {
$(id).style.display ='block';
}
var hide = function(id) {
$(id).style.display ='none';
}
JS for the hide content button:
$(document).ready(function() {
$('#hideshow').click(function() {    
if ($(this).text() == '▼ VIEW CONFIGURATION ▼') {      
$(this).html('▲ HIDE CONFIGURATION ▲')
} else {
$(this).html('▼ VIEW CONFIGURATION ▼');
}
$('#topContainers').slideToggle(400);
});
});
I cant figure out what in the popup JS code is causing the button not to work.
you are using the jquery library which uses the symbol $ and then in your popup.js you are overwriting that symbol and assigning it to a shortcut to the getElementById function, losing the reference to the jquery library.
This:
$ = function(id) { return document.getElementById(id); }
overrides the jQuery method and thus your code using the default $() doesn't work any more.

Can't explicitly render Google ReCaptcha and have a callback function working

I am building a form on a website, and I am having and issue getting a function to run when the ReCaptcha is submitted. This function removes the disabled attribute on the submit button.
There is also a chance that multiple forms may be used on one page so I implemented the following solution to allow multiple captacha forms on one page:
https://stackoverflow.com/a/33535769/2506219
It seems I can either allow multiple ReCaptcha forms or have the submit button allowed but not both.
Here is the code:
HTML
<div class="g-recaptcha" data-callback="verifyCallback"></div>
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
JavaScript
<script>
var CaptchaCallback = function() {
$('.g-recaptcha')
.each(function(index, el) {
grecaptcha.render(el, { 'sitekey': 'XXXX' });
});
};
function verifyCallback() {;
$('#submitBtn').prop('disabled', false);
}
</script>
Thank-you.
Worked it out!
I needed to call the function from the callback, having it in the HTML doesn't work
var CaptchaCallback = function() {
$('.g-recaptcha')
.each(function(index, el) {
grecaptcha.render(el, { 'sitekey': 'XXXX', 'callback': verifyCallback });
});
};

intercept or override javascript function of a class

I am new in javascript and jquery.
I have created a class having some functions in javascript.
My javascript class is written in a .js file.
common.js
var myGeneralClass = {
_show : function() {
console.log("showing some divs here");
},
_hide : function() {
console.log("hiding some divs here");
}
}
_show() and _hide() functions are bind to some events.
Now I have jsp file, from where final html is rendered.
myGeneralClass methods are called from various jsp files.
Some jsp script want to add some code in _show() and _hide() methods according to there need.
for eg :
employee.jsp
<script>
//want to add some lines of js code to _show() method plus its default code.
// intercept _show() method
_interceptShow : function() {
console.log("this line is custom for employee");
},
// override _show() method
_overrideShow : function() {
console.log("this line is custom for employee");
console.log("showing some divs here");
}
</script>
Can I override OR intercept methods in javascript?
Can it be possible ?
If yes then how?
For adding more code in method:
use this:
var temp = myGeneralClass._show;
myGeneralClass._show = function(){
temp();
// more code
}
for overriding:
myGeneralClass._show = function(){
// new code
}

Can some tell me where is the error? saying $ not defined, object expected

saying $ not defined, object expected.. actually i want to verify if all set of radio button check when a button is clicked! help plz
<script type="text/javascript">
$(document).on('click', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.qselections').each(function () {
// Question text
var question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
});
</script>
Did you forget to include the jquery.js file in your markup before your code?
A generally accepted way to set up your script references is as follows (there are others, this isn't the be-all-end-all):
<html>
<head>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="MyScriptFile.js"></script>
<script>
$(function() {
$(document).on('click', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.qselections').each(function () {
// Question text
var question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
});
</script>
</body>
</html>
This way you can be sure that (1) your page is loaded before any scripts try to do scripty things and (2) you have included jQuery before other scripts which may want to use it.
This is not foolproof, and you may (eventually) need to use something like Require.js or as a simpler step the defer attribute.
1.Have you included Jquery lib in first script tag in your head section. In that case only your jquery based code will execute.
2.Did you wrap the code into $(document).ready() function.
3 Are you using PHP at your corners. So need to replace $ with Jquery.

Knockout not binding submit with JQuery1.10.2

EDIT:
this is actually Knockout, JQuery 1.10.2 and trying to override the jquery.unobtrusivevalidation ErrorPlacement function... stopping the submit binding work on a form element.
If I run the same code with JQuery 1.8.2 then just change my JQuery file to 1.10.2 my submit function stops firing... has anyone seen similar to this?
i'm going to post as much relevant code as I can in case its something unexpected but the main point is that submitForm bound to the form submit event perfectly well with jquery 1.8.2 and without any other changes jquery 1.10.2 doesn't touch submitForm (testing with break points and alert() statements).
All other knockout bindings still seem to work.
please help. thanks.
<html>
<head>
<script src="/Content/Scripts/jquery-1.10.2.js"></script>
<script src="/Content/Scripts/jquery-ui/jquery-ui.js"></script>
<script src="/Content/Scripts/jquery-ui-timepicker-addon.js"></script>
<script src="/Content/Scripts/knockout-2.3.0.js"></script>
<script src="/Content/Scripts/knockout-helpers.js"></script>
<script src="/Content/Scripts/knockout.mapping-latest.js"></script>
<script src="/Content/Scripts/underscore.js"></script>
<script src="/Content/Scripts/date.js"></script>
<script src="/Content/Scripts/global.js"></script>
<script src="/Content/Scripts/jquery.blockUI.js"></script>
<script src="/Content/Scripts/jquery.dirtyform.js"></script>
<script src="/Content/Scripts/bootstrap/bootstrap.js"></script>
<script src="/Content/Scripts/sessionTimer.js"></script>
<script src="/Content/Scripts/jquery.livequery.js"></script>
<script src="/Content/Scripts/Ecdm/myCode.js"></script>
</head>
<form action="/Apply" data-bind="submit: submitForm" id="myApplicationForm" method="post">
<!-- html form stuff -->
</form>
<script>
var view;
$(function() {
view = new ModelView({
formSelector: '#myForm',
});
// Base JS model
var model =
{
someProperty: '#Model.SomeProperty',
};
view.bind(model);
});
</script>
</html>
myCode.js:
function ModelView(params) {
var self = this;
// Default parameters
var args = $.extend({
formSelector: 'form' }, params);
this.bind = function (model) {
// Apply KO bindings
ko.applyBindings(self);
};
this.submitForm = function () {
var form = $(args.formSelector);
form.validate();
if (form.valid()) {
var referenceNumber = $('#ReferenceNumber');
if (a==b) {
showConfirmation();
return false;
}
g_showWait("Please wait...");
return true;
}
return false;
}
}
I solved it by using the validate declaration notation rather than directly setting the validator settings but I don't know why. If anyone could explain I would be grateful (i'm sick of looking at it:))
errorPlacement was successfully overridden and working in both cases. submit knockout binding just didn't work.
Instead of overriding the errorPlacement function like this
$("form").each(function() {
var validator = $(this).data('validator');
if (typeof validator != 'undefined') {
validator.settings.errorPlacement = $.proxy(function(error, inputElement) {
//
// do stuff with the error object
//
}, $(this));
}
});
I changed it to this just try anything and it worked:
$("form").each(function () {
var validator = $(this).data('validator');
if (typeof validator != 'undefined') {
$(this).validate({
errorPlacement: $.proxy(function (error, inputElement) {
//
// do stuff with the error object
//
}, $(this));
}
});

Categories

Resources