Knockout not binding submit with JQuery1.10.2 - javascript

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));
}
});

Related

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 });
});
};

dynamically extend jQuery plugin

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>

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.

Calling JQuery function from xhtml in external js file

I have a jquery function defined in an external js file :
myJquery.js
(function($) {
$.fn.test = function (options) {
//Extended default options
var opts = $.extend({
chars: 0
}, options);
...doSomething...
})(jQuery);
Inclding this file in xhtml as:
<script type="text/javascript" src="_/js/myJquery.js"/>
and trying to access as:
$(document).ready(function() {
$("input.testClass").each(function() {
$(this).test({
chars:10
});
});
});
But getting js error saying 'test' function not found.
Your test function is scoped to the external file space, not the global environment. If you are sure that jQuery has command of the $ then append your function without the function($) wrapper.
EDIT: while the above may still be relevant for others ... it does work fine (at least for just showing the alert) with the } in place:
external file inlcuded with <script type="text/javascript" src="testing.js"></script>
(function($) {
$.fn.test = function (options) {
//Extended default options
var opts = $.extend({chars: 0}, options);
alert('boo: '+opts.chars);
}
})(jQuery);
in page:
<script type="text/javascript">
$(document).ready(function() {
$("h1").each(function() {
$(this).test({
chars:10
});
});
});
</script>

Best jQuery plugin implementation for binding JavaScript's oninput event

I know jQuery doesn't support the oninput event, so have myself started to write a plugin to do the job. Although don't understanding very well all the stuff related to events in jQuery or JavaScript I ended up with usable code that currently satisfies my requirements.
Unfortunately I think my current implementation can crash, specially when using it in conjunction with other libraries because am setting directly the oninput member of the DOM elements.
Do you know a better and portable way to solve this problem, maybe using methods such as jQuery's "on" or JavaScript "addEventListener"?
Here is a working example of the code i'm currently using:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
////////////////////////////////////////////////////////////////////////////
// jQuery plugin to bind an event handler to the "oninput" JavaScript event.
(function ($) {
// Add an "input" method to all jQuery objects
$.fn.input = function (handler) {
// iterate over all DOM elements in the jQuery object
this.each( function () {
// set a new method to run when "oninput" is fired
this.oninput = function (prevHandler) {
return function (ev) {
// call previous handler if exists
if( typeof prevHandler === 'function' ) {
prevHandler.call (this, ev);
}
// call new handler
handler.call (this, ev);
};
}(this.oninput); // immediate evaluation, pass current handler as argument
});
};
} (jQuery));
////////////////////////////////////////////////////////////////////////////
</script>
<script type="text/javascript">
// Test the plugin
$(document).ready (function () {
$('#one').input (function () {
alert ('Input on one: ' + $(this).val());
});
$('#three,#four').input (function () {
alert ('Input on three or four: ' + $(this).val());
});
$('#one,#two,#three').input (function () {
alert ('Input on one, two, or three: ' + $(this).val());
});
$('#one,#two,#three,#four').input (function () {
alert ('Input on any: ' + $(this).val());
});
});
</script>
</head>
<body>
<input id='one'/><br/>
<input id='two'/><br/>
<input id='three'/><br/>
<input id='four'/><br/>
</body>
</html>
Thanks in advance!!
jQuery's 'on' can handle any event so you could simply do something like this:
(function() {
var outputElement = document.getElementById('mirror-input');
$('#input-stuff').on('input', function (event) {
outputElement.innerText = event.target.value;
});
}())
http://jsfiddle.net/YCAtZ/

Categories

Resources