Im using html5 capacities to read image width and height before submitting...
Well, this is not happening exactly, it seems like the time needed for the functions:
reader.readAsDataURL();
reader.onload = function();
image.onload = function();
To read the file is way too much than the time my form is able to wait before sending the pic.
I can check that the beforeSubmit function is triggered, but the form is submitted before it finishes.
Another weird thing is that I have replaced the beforeSubmit function content with a simple return false sentence and the form is being submitted anyway.
Am I missing something regarding the beforeSubmit option in ajaxSubmit?
The beforeSubmit function has been minimized to a return false statement, here comes the submit (the form is inside a dialog(), may be this the clue?:
$('.block .imgpop').on("click",function()
{
type = $(this).attr('emimage');
currentype = type;
options =
{
type: 'POST',
target: '#uploadverbose',
beforeSend: beforeSubmit,
resetForm: true,
success: showResponse,
data: { type: $(this).attr('emimage'), tempname: $(this).attr('id'), maxsize: imgsizesW[$(this).attr('emimage')] },
dataType : "text"
};
$('#uploadbitch').dialog(
{
closeOnEscape: true,
width: 800,
modal: true
});
return false;
});
$(document).on("click","#MyUploadForm input[type=submit]", function(e, submit)
{
if (!submit) e.preventDefault();
$('#MyUploadForm').ajaxSubmit(options);
});
$(document).on("submit","#MyUploadForm", function(e, submit)
{
e.preventDefault();
$('#MyUploadForm').ajaxSubmit(options);
});
If you try to handle onclick on submit button then it doesn't stop form from submitting.
It may bot be exactly the answer, but it works. I have place all the image testing in the input field with a "change" event and it works just fine for me. Precocity in the form submitting is still unsolved.
Related
I'm trying to call a funtion in textextjs method-
//my function
function GetAreaTags() {
return "some text";
}
//textext initializtion
$('#territory').textext({
plugins: 'tags prompt focus autocomplete ajax',
ajax: {
url: '/Admin/Search/GetTerritorySuggestions?area=' + GetAreaTags(),
dataType: 'json',
cacheResults: false
}
});
But GetAreaTags() is not being called. How can i make it happen?
It should work... But try this:
function GetAreaTags() {
return "some text";
};
var yourObj= {
plugins: 'tags prompt focus autocomplete ajax',
ajax : {
url: '/Admin/Search/GetTerritorySuggestions?area=' + GetAreaTags(),
dataType: 'json',
cacheResults: false
}
};
$('#territory').textext(yourObj);
console.log(yourObj.ajax.url);
If that doesn't work out try this:
function GetAreaTags() {
return "some text";
};
var yourObj= {
plugins: 'tags prompt focus autocomplete ajax',
ajax : {
url: function() {return '/Admin/Search/GetTerritorySuggestions?area=' + GetAreaTags()},
dataType: 'json',
cacheResults: false
}
};
$('#territory').textext(yourObj);
console.log(yourObj.ajax.url);
Check the console both times to see if your url is what you desire.
[EDIT: I rejected the edit by mistake, sorry about that]
Edit2
From s.k.paul's comment:
GetAreaTags() should execute every time i type in that textbox.
However, console says- 1. /Admin/Search/GetTerritorySuggestions?area=
2. localhost:12788/Admin/Dashboard/…}&q= 404 (Not Found)
Therefore you need another event handler to dynamically change the url (the plugin must be recalled with another url):
function GetAreaTags() {
return "some text";
};
$("#territory").keyup(function() {
var yourObj= {
plugins: 'tags prompt focus autocomplete ajax',
ajax : {
url: function() {return '/Admin/Search/GetTerritorySuggestions?area=' + GetAreaTags()},
dataType: 'json',
cacheResults: false
}
};
$('#territory').textext(yourObj);
console.log(yourObj.ajax.url);
});
However, this may be very heavy... The plugin expects you to have a single reference for your auto-complete resource. If you're dynamically changing it, it may reset the already existing stuff.
Edit3
Edit 2 : textextjs does not work at all now. And, url function returns
whole function text
This means the plugin doesn't handle well being recalled twice or more times in the same element. The only possible solution I am seeing is to change the plugin's code in order to dynamically change the resources according to your function...
Which makes me wonder, if it's easier for you to allow the user to have a broader data resource (include all areas) when typing, this way there would be only one URL and the plugin wouldn't have any trouble with that.
I am putting together a quiz system using the multipage form jQuery script and I would like to be able to warn the user if tries to close the page. I managed to do this just fine using the code below:
$(document).ready(function($) {
window.onbeforeunload = function(){
return 'Sure you want to close the page?';
};
});
My problem is that when I try to submit the form and post the results I get the warning asking me if I want to navigate away from this page. This is the code:
$('#quizForm').formwizard({
validationEnabled: true,
focusFirstInput : true,
formOptions: {
beforeSubmit: window.onbeforeunload = null,
resetForm: true
}
});
What am I doing wrong?
LE: I created this fiddle maybe someone can help me out, I am running out of ideas.
http://jsfiddle.net/awLYY/5/
first, you don't need to wait for the DOM to be ready in order to attach an onbeforeunload handler.
second, since the onbeforeunload is a function, you can choose wither to return a string or return nothing in case you're submitting some data to the server
var isFormBeingSubmitted = false;
window.onbeforeunload = function() {
if( isFormBeingSubmitted ) {
return;
}
return 'Sure you want to close the page?';
};
// now before you submit your form, just enable the isFormBeingSubmitted
$('#quizForm').formwizard({
validationEnabled: true,
focusFirstInput : true,
formOptions: {
beforeSubmit: function() {
isFormBeingSubmitted = true;
return true;
},
resetForm: true
}
});
To answer my own question, all I had to do was to add to the formwizard options:
formPluginEnabled: true
Now everything is working fine. Thanks
I'm trying to get some client side validation working to prevent a form submission occurring if an object has no value. I've been plugging away at this for a while now but cannot get a satisfactory solution.
My form submission Js looks like this:
$(document).ready(function () {
$('#localUsersDateTime').val(setLocalDateTime());
$('#createentry').ajaxForm({
beforeSubmit: checkTextObjHasValue($('#newentry'), 'You need to add some text.'),
dataType: 'json',
success: function (result) {
$('#entries-list').prepend('<li>' + $('#newentry').val() + '</li>');
$('#newentry').val('').blur();
},
error: function (xhr)
{
try {
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch (e) {
alert('Oops, Something very bad has happened');
}
}
});
return false;
});
However when the page loads it runs my checkTextObjHasValue() specified in the beforeSubmit: function so that check needs to only execute on actual form submission.
function checkTextObjHasValue(obj, message) {
if ($(obj).val() === '') {
alert(message);
return false;
}
return true;
}
How can I prevent this beforeSubmit: callback from being executed when just loading the page and only execute on actual form submission?
The beforeSubmit option expects a reference to a function. You were immediately calling a function. Try using this:
beforeSubmit: function () {
return checkTextObjHasValue($('#newentry'), 'You need to add some text.');
},
The added return allows for the submission to cancel if false is actually returned (which is possible in checkTextObjHasValue under a certain condition).
Technically, it could've worked if you returned a function from checkTextObjHasValue, but I think this way is a little cleaner. And it lets you customize it in case you want to validate several fields.
UPDATE:
Like in the documentation for the plugin, you could take this approach:
beforeSubmit: beforeSubmitHandler,
And then define a function separately like this:
function beforeSubmitHandler() {
return checkTextObjHasValue($('#newentry'), 'You need to add some text.');
}
I have a very simple scenario where I want to POST the form using JQuery's ajax() method but perform request some confirmation from the user before actually performing the post.
I have a JQuery UI dialog with localized buttons in place in case you wonder what all the code with buttons below is about.
This is my code so far:
var i18n_deleteButtons = {};
i18n_deleteButtons[i18n.dialogs_continue] = function () {
return true;
$(this).dialog('close');
};
i18n_deleteButtons[i18n.dialogs_cancel] = function () {
return false;
$(this).dialog('close');
};
$('#delete-dialog').dialog({
open: function () {
$(this).parents('.ui-dialog-buttonpane button:eq(1)').focus();
},
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons: i18n_deleteButtons
});
$("form#form_attachments").submit(function (event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this), url = $form.attr('action');
// build array of IDs to delete (from checked rows)
var jdata = { 'attachmentIdsToDelete': [] };
$('input:checked').each(function () {
jdata['attachmentIdsToDelete'].push($(this).val());
})
$.ajax({
beforeSend: function (request) {
// Return false if you don't want the form submit.
$('#delete-dialog').dialog('open');
},
url: url,
type: "POST",
dataType: "json",
data: jdata,
traditional: true,
success: function (msg) {
$('#msg').html(msg);
}
});
});
The dialog actually opens up fine but clicking at any of the buttons results in nothing happening. The post doesn't happen and the dialog does not close regardless of which button was clicked.
How can I make this work?
Why not move the actual ajax call from the submit handler and trigger it when pushing a button in the delete dialog?
You could store you ajax call in a separat function and pass this functions and the url as parameters to the confirmation routine.
[pseudo code]
function callAjax() {
...
}
function submitHandler() {
confirmDialog({callback:callAjax,param:you_url});
}
function confirmDialog(obj) {
$('#yes_btn').click(function() {
// call the callback
obj.callback(obj.param);
});
$('#no_btn').click(function() {
// just close the dialog
});
}
This way the confirmDialog don't have to know anything about the ajax call, it will just execute the callback with the given parameter when the user clicks ok.
Because the default jquery UI dialog is a bit cumbersome for regular use and trouble to configure in some custom scenarios I looked around and found this Easy Confirm plugin which is based upon jquery&jquery UI default stuff. It also allows for very simple internationalization.
https://github.com/wiggin/jQuery-Easy-Confirm-Dialog-plugin
I'm checking my form with RSV validator. Want to get work following: Let's say user opened page for the first time. After filling all text input boxes, when user clicks #submit_btn FOR THE FIRST TIME, the form submit function fires RSV (validator), validator checks if there is any error. If all right, posts data via ajax, else RSV shows error messages array with the help of alert(). THIS PROCEDURE ONLY FOR THE FIRST TIME
BTW: RSV - validator. If no error occured during validation process the myoncomplete() function returns 1.. If something went wrong it alerts. Got from here
I can't get it work. Please help me to fix logic/code mistakes. Thx in advance
My JS
var int=null;
var counter=0;
function myOnComplete() {
return 1;
}
$(document).ready(function () {
$("#add_form").RSV({
onCompleteHandler: myOnComplete,
rules: [
"required,name,Page name required",
"required,title,Page title required.",
]
});
$("#add_form").submit(function (e) {
e.preventDefault();
dataString = $("#add_form").serialize();
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
//do something if ajax call is success
int = setInterval(call, 3000);
var message = result.msg;
var err = result.err;
if (message != null) {
$.notifyBar({
cls: "success",
html: message
});
}
if (err != null) {
$.notifyBar({
cls: "error",
html: err
});
}
},
error: function (e) {
//ajax call failed
alert(e);
}
});
});
$("#submit_btn").click(function () {
if(counter===0){
if(myOnComplete()===1) $('#add_form').submit();
else return false;
}
else $('#add_form').submit();
counter++;
});
$('#autosave').click(function(){
if($(this).is(':checked')){
int = setInterval(call, 3000);
$('#submit_btn').attr({'value':'Save&Exit'});
}
else{
$('#submit_btn').attr({'value':'Save'});
clearInterval(int);
}
});
});
function call() {
$('#add_form').submit();
}
Looking through the RSV code it looks like whatever you attach RSV to has its submit rebound to validate the data using .RSV.validate()
As seen here:
$(this).bind('submit', {currForm: this, options: options}, $(this).RSV.validate);
});
Which means that if you use .submit() you are calling .RSV.validate also.
So once you validate the info try binding your submit to the standard submit function.
Edit: To help explain
When you use
$("#add_form").RSV({...});
The RSV javascript code is binding .RSV.validate() to the submit event of your add_form element. Meaning when you submit your add_form form .RSV.validate() is being called before the submit.
Try running the script code below with and without the .RSV() call
This script will log ALL handlers for ALL events on the add_form element. You notice that calling $element.RSV({...}) attaches a second event handler to the submit event of the add_form element. I am unsure of the best way to access this event handler to .unbind() it. Good luck :)
jQuery.each($('#add_form').data('events'), function(i, event){
jQuery.each(event, function(i, handler){
console.log(handler);
});
});
OK, to my understanding now you only want to validate the first set of data and if that validates correctly trust the user, i got this working on jsFiddle with an easy example, i guess you can make use of that
http://jsfiddle.net/WqnYa/9/
Basically what i do is that i catch the submit button click and not the forms submit function, maybe it can be done that way, too. I assign a class "needsvalidation" and when ever the first validation passes, i simply remove that class. And if that class is not present, the validation will not be initialized due to $(this).hasClass('needval')
If that's not what you're looking for then your question needs way more clarity :( hope this helps though!