Hey guys i have looked as much as i could and i could not find an answer, i am creating an admin interface that has forms all over the place and i would like to use the same jquery code for all of them, i have some code that is getting the job done but i would like to know if there is a more efficient way to do it. here is the code
function submitForm( formname )
{
$.ajax
({
type:'POST',
url: 'session.php',
data: $(formname).serialize(),
success: function(response)
{
if( $('#message_box').is(":visible") )
{
$('#message_box_msg').html ('')
$('#message_box').hide();
}
$('#message_box').slideDown();
$('#message_box_msg').html (response);
}
});
return false;
}
Now my forms look something like this:
<form id="adminForm" action="session.php" method="post" onsubmit="return submitForm('#adminForm');">
Now my question is... is there a simpler way to do this, like without having to provide the submitForm() function with the form id every time?
Thanks in advance!
You may want to delegate a handler to document or other permanent asset in the page(s) to account for any ajax loaded forms. This will replace your inline onsubmit
$(document).on('submit','form', function(){
var allowSubmit=false,
noSubmitMessage="Can't submit", /* can change message in various places in following code depending on app*/
$form=$(this);/* cache jQuery form object */
if( $form.hasClass('doValidation')){
/* class specific code to run*/
allowSubmit = validationFunction();
}
if( allowSubmit){
var data=$form.serialize()
/* do ajax*/
}else{
/* user feedback*/
alert( noSubmitMessage);
}
return false;
});
Yes, define a common class for all your forms, and use
$(".form_class").submit(function() {
//stuff that gets executed on form submission ...
return result;
})
And dump the inline "onsubmit". It's also cleaner to do this in general, as it separated view from behaviour.
Related
I'm writing a script for a website I'm currently building.
var ownerForm = $('#item_owner_form_');
ownerForm.submit(function(ev) {
//$.ajax({
//'url': 'checklist_changeowner.php',
//'type': 'GET',
//'dataType': 'json',
//'data': {owner: blabla, item: blablbalba, checklist: blabla},
//'success': function() {
//
//}
//});
alert(ownerForm.serialize());
ev.preventDefault();
});
As you've probably already seen, I've set a fixed id for the ownerform (in this case #item_owner_form_) However, I am creating lots of forms through PHP and this is not what I'm looking for. For example, a form that will be generated could be identified as #item_owner_form_42 or as #item_owner_form_913.
Is there a universal character to make sure the ownerForm variable will use all of the forms that start with #item_owner_form_ ? Help would be much appreciated!
You class for that. It can be common for many(similar) elements.
So, your all forms would look like this,
<form id="item_owner_form_1" class="commonItemForm">
</form>
<form id="item_owner_form_2" class="commonItemForm">
</form>
And use the class in jQuery like this,
$('.commonItemForm').submit(function(ev) {
alert($(this).serialize());
ev.preventDefault();
// This function will get triggered for every form which has commonItemForm class.
});
I am developing a tool for my Wordpress website using jQuery, I am quite new at this but what I'm trying to do is not that hard.
My script is enqueued, i've read that with the NoConflict mode i can't use $ so I use jQuery instead.
function Calculator()
{
var result = jQuery('result');
if (jQuery('day').value == "" || jQuery('month').value == "" || jQuery('year').value == "") {
return;
}
result.update('<span class="result">processing</span>');
jQuery('form').request({
onComplete: function(transport) {
result.hide();
result.update(transport.responseText);
new Effect.Appear(result, { duration: 0.5 } );
}
});
}
My problem is I got error everywhere :
update is not function
request is not function
etc...
There is something i'm obviously doing wrong but can't figure out what...
thanks a lot !
The errors you are seeing ("update is not function request is not function") describe the problem - those really are not jQuery functions.
It looks like you're trying to update an HTML element with ID or class "result". To do that, use .html():
var result = jQuery('.result'); // "." to select the element with class result
result.html('something');
For .request, it looks like you are trying to do a POST or GET of a form. If so, use .ajax(), .post(), or .get(). Note though you'll need to add a few more details, eg:
jQuery('form').ajax({
type: "POST",
url: someurl,
data: somedata,
onComplete: ...
});
Also, if your Calculator() function can be called while the page is loading, make sure it (or whatever calls it) is wrapped in document.ready:
jQuery(document).ready(function () {
...
});
An unrelated issue, to check the value of say a form input with class "day", you need to use:
jQuery('.day').val()
if you are fetching the value using class then you have to do it like this:
jQuery('.result').val()
or if using id use it like:
jQuery('#result').val()
in jquery we use .val() function to get value instead of value.
Is update, request exists in jquery?
you can use like this rather than writing again and again.
var j = jQuery.noConflict();
j(".result").html("<span>Processing..</span>");
This might be an impossible question to answer but i will try to provide you with a lot of information so that you might know the problem and maybe you have had the same problem before.
I have a form that i serialize with this method:
//Sends a serialized string with all form keys from DementiaPrototype to RiskScore-view
$(document).on("click", "#btnsubmit", function () {
if (validateForm() == true) { //a method for validating the form
if (validatepersonid() == true) { //a method for validating the form
if(validatenr() == true){ //a method for validating the form
$("#PersonBMI").removeAttr('disabled');
$.ajax({
url: "/Home/RiskScore",
type: "post",
data: $("form").serialize(),
success: function(result) {
$('.content-wrap').html(result);
//calls the functions that animates the thermometer on page loaded
countScore();
countScores();
}
});
}
}
}
});
the two methods after sucess countScore(); and countScores(); will take lot's of input values and from the form and do some calculating and then show it in a thermometer on the next page. They booth look almost the same except some different use of textboxes. The problem is that countScores() does what it should but i can't debugg it. countScore() does nothing and i can't debugg that either. The way i can't debugg it is that it just don't use the method and don't go through my debuggs. It's very strange and i just can't solve the problem :S No one on my company knows what is going on. I have deleted all cache so that can't be the problem(If it could have been).
Make sure you cancel the default action of the form to prevent the browser from redirecting away:
$(document).on("click", "#btnsubmit", function (e) {
e.preventDefault();
... your code comes here
});
I've noticed, that sometimes my validation code works wrong:
var $validator = $("#checkoutForm").validate();
...
if (!$validator.element($sameShippingAddress)) {
...
}
Debugging with Firebug showed, that sometimes $validator.element($sameShippingAddress) would return undefined (I guess it just does not wait till response is returned) and that would be assumed as false, even if element is valid.
If add code like this before if statement, everything works fine:
while (validator.element($sameShippingAddress) !== undefined) {
}
Question is if that is right solution and there's no better way to handle problem with validation plugin itself?
Update: I'm using http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Infinite while loop on validator variable is not a good choice. Instead use the code below that utilise Javascript timer. You can show animated processing/server response graphics after validate() method.
var validator = $('#resetpassword').validate({///your code...})
doTimer();
function timedCount()
{
t=setTimeout("timedCount()",1000);
}
function doTimer()
{
if (validator === undefined)
{
timedCount();
}
}
if(validator==true)
$('#form').ajaxSubmit(options);
It's hard to tell how you are handling successful submissions or if you uses the css class to denoted required fields, but the following is how it's done in the demo for the plugin:
$.validator.setDefaults({
// code to be executed on submit
submitHandler: function() { alert("submitted, replace this with your server request");}
});
$().ready(function() {
// validate the comment form when it is submitted
// use css class .required for fields you want the validator to check
// if your form is valid then it is handled by the submitHandler
// if not the plugin displays error messages
$("#checkoutForm").validate();
//validate can take a block for custom validation and error messages
});
Hope this helps you find a solution and isn't just more of the same (also just realized this question is a year old, but I already wrote this so...)
Obiously, it is not the best solution. Instead add
if (!$validator.element($sameShippingAddress)) {
...
}
in the Ajax callback function.
I'm trying to create some javascript validation for my web app and it's all going pretty well except I do not want my script to look for something to validate all the time.
Let's say I have two things I want to validate for but they do not occur on the same page. They are on '/page1' and 'page2' and I don't want my validator for page1 to run on page2.
That should be possible through object literals right?
Something like this:
var validations =
{
page1validation :
{
init : function()
{
// validation page 1
}
}
page2validation :
{
init : function()
{
// validation page 2
}
}
}
So I need to call these validation methods like validations.page1validation.init() and I guess I could do this with inline javascript in each haml view where I have a form that needs validation.
%form{:action => ""}
%input{:type => "text"}
%input{:type => "submit", :value => "save"}
:javascript
$(function() {
validations.page1validation.init();
});
But there must be a better solution - I just can't think of one right now. So what would you do to make sure the validator doesn't try to validate all the time?
Oh and the inline javascript won't work if I put the javascript at the bottom in my layout file...
The simplest way to do what you want is to make the forms different, either with a different id or class.
Then your validations can use that difference to "target" each form independently. You don't need the extra "namespace" with that approach. Instead, you do something like this.
$(function() {
page1validation();
page2validation();
});
function page1validation() {
var form = getElementById('form1'); // form1 is the first form
if(!form) then return;
// .. perform validations in form 1
}
function page2validation() {
var form = getElementById('form2');
if(!form) then return;
// .. perform validations in form 2
}
Also, I'd advice you to invest some time in learning a js library like jQuery. It provides some built-in methods that will make the code above much smaller.