JavaScript processing Form sample (JavaScript submit form) _ Basics

Source: Internet
Author: User
Tags eval form post session id visibility


Working with a variety of forms, as well as links, buttons, generic components





 code as follows:



/**


* Generic Form Processing JS


* @author Anthony.chen


*/





/**
* Push button action [btn_action]data into form
* If There is prescript, run the pre script
*/
"Use strict";
All Ajax request are synchronized by default
var ajaxsynchronized = true;
All Ajax request'll is unblock by default
var ajaxautounblock = true;



var Ajax_action_button = function (e) {
var btn = $ (this);
ADD Prescript
var pre_script;
if (Pre_script = btn.attr ("Pre_script")) {
var ret = eval (pre_script);
if (Ret==false) {
return false;
}
}
var btn_action = btn.attr (' value ');
if (btn_action) {
$ (this). Closest (' form '). Data (' Btn_action ',
{name: ' Btn_action ', value:btn_action}
);
}
};



/**
* Update the extra form, Key and Value, with form element, FormElement
*/
var ajax_update_post_data = function (Formele, K, v) {
var form = $ (Formele);
var post_data = form.data (' Post_data ');
if (Post_data = = undefined) {
Post_data = {};
}



if (v = = undefined) {
Delete Post_data[k];
}else{
Post_data[k] = v;
}
Form.data (' Post_data ', post_data);
return true;
};



/**
* Bool checkbox is special checkbox which needs to keep uncheck value
* and post with Ajax form, the form being in the parent
*/
var bool_checkbox = function () {
var IPT = $ (this);
var Formele = ipt.closest ("form");
var _check = Ipt.prop ("checked");
if (_check) {
Ajax_update_post_data (formele,ipt.attr (' name '));
}else{
Ajax_update_post_data (formele,ipt.attr (' name '), ' f ');
}
};



/**
* Init the spin number
*/
var spin_number = function () {
var spin = $ (this);
var config = {
Lock:true,
Imagebasepath: ' {webpath}/css/images/spin/',
Btncss:null,
Txtcss:null,
Btnclass: ' Spin_btn ',
};
var interval = spin.attr (' interval ');
if (interval) {
Config.interval = interval;
}else{
Config.interval = 1;
}



var min = spin.attr (' min ');
if (min) {
config.min = min;
}



var max = spin.attr (' Max ');
if (max) {
Config.max = max;
}



Spin.spin (config);
return true;
};



/**
* Init the date input
*/
var date_input = function () {
var IPT = $ (this);
var config = {
offset:[4,0],
Selectors:true,
Lang: ' {lang} ',
Firstday:1,
Format: ' Yyyy-mm-dd ',
};

var min = ipt.attr (' min ');
if (min) {
config.min = min;
}



var min = ipt.attr (' min ');
if (min) {
config.min = min;
}



Ipt.dateinput (config);
return true;
};




/**
* Init the Timepicker
*/
var time_picker = function () {
var IPT = $ (this);
var config = {};



var step = ipt.attr ("step");
if (step) {
Config.step = step;
}



Ipt.timepicker (config);
return true;
};



/**
 * Generic Ajax Form post function
 * if Btn_action is set, then add data into Form
 * If R Eturi is set, redirect to Returi
 * if reload are set, reload
 * else show blocks message
 *
&NB sp;* the form would be validated.
 */
var ajax_form_post = function (e) {
 var form = $ (this);
 var Pre_script;
 if (pre_script = form.attr ("Pre_script")) {
  var ret = eval (pre_script);
  if (ret==false) {
   return false;
 &NBSP}
 }
 var errhint = Form.find (". Formerror").  if (errhint.size () = = 0) {
  errhint = $ ("#pageError");
&NBSP}
 errhint.text ("). Hide ();



Cleanup the Pageerror
if (!e.isdefaultprevented ()) {
Hide all. Formerror
$.blockui ({message: "{__ (' l_processing ')}"});
var Formarray = Form.serializearray ();
var btn_action_data;
var btn_action;
if (Btn_action_data = Form.data (' btn_action ')) {
Formarray.push (Btn_action_data);
Form.removedata (' btn_action ');
Btn_action = Btn_action_data.value;
}else{
Btn_action = ';
}


Console.log (' btn action: ' +btn_action);


ADD Extra Data


var post_data;


if (Post_data = Form.data (' post_data ')) {


For (var k in post_data) {


If POST_DATA[K] is array,need the more todo


Formarray.push ({name:k, value:post_data[k]});


}


Form.removedata (' Post_data ');


}





$.post (form.attr (' action '), Formarray,function (JSON) {


if ($ (window). Data (' blockui.isblocked ') = = 1) {


$.unblockui ();


}


if (Json.code = = True) {


var Returi = "";


var retdata = "{__ (' l_processed ')}!";


if (json.data) {


Retdata = Json.data;


}

TODO Add suppport to allow save and stay


if (btn_action = = ' Reqonly ') {


if (Returi = form.attr (' Returi ')) {


$ (window). Data (' Blockui.returi ', Returi);


Ajaxautounblock = false;


}


$.blockui ({message:retdata, css:{cursor: ' pointer ', padding: ' 4px ', border: ' 3px solid #CC0000 ',}, overlaycss:{cursor: ' Pointer '}});


$ (". Blockui"). AddClass ("Blockwarn");


//if there is Returi set, then return to URI


else if (Returi = form.attr (' Returi ')) {


window.location = Returi;


Else If reload is set, then would be reload


}else if (form.attr (' reload ')!=undefined) {


Window.location.reload ();


}else{


$.blockui ({message:retdata});


$.unblockui ();


}


}


else{


if (typeof (json.data.errmsg) = = ' String ') {


Errhint.html (Json.data). Show ();


$.blockui ({message:json.data, css:{cursor: ' pointer ', padding: ' 4px ', border: ' 3px solid #CC0000 ',}, overlaycss:{ Cursor: ' pointer '}});


$ (". Blockui"). AddClass ("Blockwarn");


}else{


Errhint.html ("{html::text (' E_form ')}"). Show ();


For (var p in Json.data) {


var msg = json.data[p];


Process hidden Value,none Hidden input should has refid refered to hidden value


Showing the Server message to ref


var ele = Form.find ("[Type=hidden][name=" +p+ "]");


if (ele.length) {


Delete JSON.DATA.P;


refID = ele.attr ("id");


RefName = Form.find ("[hidden-id=" +refid+ "]"). attr ("name");


json.data[refname]=+msg;


}

Muti checkbox


var ele = Form.find ("[Type=checkbox][name= '" +p+ "[]]");


if (ele.length) {


Delete JSON.DATA.P;


refname = p+ ' [] ';


json.data[refname]=+msg;


}


@END


}


}


/*


* Checking The hidden values


*/


Form.data ("Validator"). Invalidate (Json.data);


}}, ' JSON ';


E.preventdefault ();


}else{


Errhint.html ("{html::text (' E_form ')}"). Show ();


}


};


/***
* Reset the input
*/
var Ajax_post_form_hidden = function () {
var form = $ (this);



  form.find ("[Hidden-id]"). each (function () {
   //clear the message of Reference
   var input = $ (this);
   var refID = input.attr ("Hidden-id");
   var field = $ ("#" + refID + "");
   //setup the "clear of ErrMsg
   //monitor" The Change event on ID element, remove ER ROR message
   //of Real input
   field.change (function () {
     //hidden input
    var hinput  = $ (this);
    //real input
    var rinput = $ ("[hidden-id=" +hinput.attr ("id") + "]" ). (a);
    form.data (' validator '). Reset (rinput)
    
   });
  };



var validate_hidden_id = function (input) {
var refid = input.attr ("Hidden-id");
var field = $ ("#" + refID + "");
var msg = field.attr (' msg ');
if (!msg) {
msg = "{__ (' E_not_empty ')}";
}



Return Field.val ()? true:msg;
};



var data_equals_validate = function (input) {
var field;
var name = input.attr ("Data-equals");
field = This.getinputs (). Filter ("[name=" + name + "]");
return Input.val () = = Field.val ()? true: [name];
};



/**
* Ajax request through link
* If confirm is set, confirm before send request
* Support Returi and Reload
* Else Show blocks message
*/
var ajax_link_req = function () {
var L = $ (this);
var hint = l.attr (' hint ');
if (hint) {
var errhint = $ (l.attr (' hint '));
Errhint.text ("). Hide ();
}
If the Confirm message was set, then should be confirmed from client
if (l.attr (' confirm ')) {
if (!confirm (l.attr (' confirm ')) {
return false;
}
}



$.blockui ({message: "{__ (' l_processing ')}"});



var pre_script;
if (Pre_script = l.attr ("Pre_script")) {
var ret = eval (pre_script);
if (Ret==false) {
return false;
}
}



var block = l.attr (' block ');
if (block!= undefined) {
Ajaxautounblock = false;
}



$.get (l.attr (' href '), function (JSON) {
if (Json.code = = True) {
var retdata = "{__ (' l_processed ')}!";
var Returi;
If success to execute funtion for each
var successfunc = l.attr (' success ');
if (Successfunc) {
L.each (Window[successfunc]);
}


if (json.data) {


Retdata = Json.data;


}


IF Require Warning Before


if (l.attr (' value ') = = ' Reqonly ') {


alert (retdata);


}else if (Returi = l.attr (' Returi ')) {


window.location = Returi;


}


else if (l.attr (' reload ')!=undefined) {


Window.location.reload ();


}


else{


$.blockui ({message:retdata, css:{cursor: ' pointer ', padding: ' 4px ', border: ' 3px solid #CC0000 ',}, overlaycss:{cursor: ' Pointer '}});


$ (". Blockui"). AddClass ("Blockwarn");


}


}else{


$.unblockui ();


Only could support Text ErrMsg


if (hint) {


Errhint.text (Json.data). Show ();


}else{


alert (json.data);


}


}}, ' JSON ';


return false;


};


/**
* Supporting the button base navigation
* Only jump to new href
*/
var btn_nav = function () {
var input = $ (this);
var href = input.attr ("href");
if (href) {
window.location = href;
}else{
Alert ("Href not set");
}
return false;
};



/**
* Support Button Base Ajax Get method request
* Support Returi and reload
*/
var btn_req = function () {
var input = $ (this);
var href = input.attr ("href");



var hint = input.attr (' hint ');
if (hint) {
var errhint = $ (hint).
if (errhint.size () = = 0) {
Errhint = $ ("#pageError");
}
Errhint.text ("). Hide ();
}



var block = input.attr (' block ');
if (block!= undefined) {
Ajaxautounblock = False
}


$.get (Href,function (JSON) {


if (Json.code = = True) {


var Returi;


if (Returi = input.attr (' Returi ')) {


window.location = Returi;


}


else if (input.attr ("reload")!=undefined) {


Window.location.reload ();


}else{


var retdata = "{__ (' l_processed ')}!";


if (json.data) {


Retdata = Json.data;


}


$.blockui ({message:retdata,css:{cursor: ' pointer '},overlaycss:{cursor: ' Pointer '}});


}


}else{


if (hint) {


$.unblockui ();


Errhint.html (json.data.errmsg). Show ();


}else{


$.blockui ({message:json.data.errmsg, css:{cursor: ' pointer ', padding: ' 4px ', border: ' 3px solid #CC0000 ',}, Overlaycss: {cursor: ' pointer '}});


$ (". Blockui"). AddClass ("Blockwarn");


}


}


}, ' json ');


return false;


};





/**
 * Generic Ajax Checkbox
 * The default action is prevented and submit real request through URL
 */
var ajax_checkbox = function () {
 event.preventdefault ();
 var action = $ (this);
 var url = action.attr (' url ');
 var _check = Action.prop ("checked");
 console.log (_check);
 var op;
 if (_check) {
  op = "1";
 }else{
  op = "0";
&NBSP}
 $.get (url + op, function (JSON) {
  if (Json.code = = True) {
     if (_check) {
     action.prop ("checked", true);
    }else{
     action.prop ("checked", false);
   &NBSP}
    return true;
   }else{
    return false;
   }
 }, ' json ');
};




/**
* Crete Root picklist
*/
var picklistinit = function () {
var _select = $ (this);
var _hidden_id = _select.attr (' Hidden-id ');
var _un = _select.attr (' un ');
var _lovchildren = _select.data (' Lovtree '). C;
var _rowvalue = _select.data (' Rowvalue ');



$ ("<OPTION>"). Append ("{__ (' L_select ')}"). Appendto (_select);
for (Var _kid in _lovchildren) {
var _lov = _lovchildren[_kid][' Lov '];
$ ("<OPTION>"). Val (_lov.lov_id). Append (_LOV.V). attr (' K ', _lov.id). attr (' Is_leaf ', _lov.is_leaf). Appendto (_ Select);
}
_select.change (Picklistchange);



Select the list
if (_rowvalue) {
_select.find ("[value=" +_rowvalue[0]+ "]"). Prop ("selected", true);
_select.change ();
}
return true;
};



/**
* Select Pick List
*/
var picklistchange = function () {
var _select = $ (this);
var _hidden_id = _select.attr (' Hidden-id ');
var _un = _select.attr (' un ');



Remove all the subsequent
var _lovtree = _select.data (' Lovtree ');
var _rowvalue = _select.data (' Rowvalue ');



_select.nextall (). remove ();



This is value of the current Select
var _selected = _select.find (': Selected ');
if (_selected.attr (' is_leaf ') = = "{db::t}") {
$ ("#" +_hidden_id). Val (_select.val ());
_select.after (" ')";
}else{
var _val = _select.val ();
var _k = _selected.attr (' k ');



  //getting Children list
  if (_lovtree.c[_k].c = = undefined) {
    return false;
  }
  var _c_lovtree =  _lovtree.c[_k];



  var _c_select = $ (' <SELECT> '). Data (' Lovtree ', _c_lovtree).
   data (' Rowvalue ', _rowvalue).
   attr (' Hidden-id ', _hidden_id). attr (' un ', _un).
   attr (' name ', _un+ ' _ ' +_k);
  $ ("<OPTION>"). Append ("{__ (' L_select ')}"). Appendto (_c_select);
  //building the option list
  for (var _kid in _c_lovtree.c) {
   var _ Lov = _c_lovtree.c[_kid][' Lov '];
   $ ("<OPTION>"). Val (_lov.lov_id). Append (_LOV.V). attr (' K ', _lov.id). attr (' Is_leaf ', _ lov.is_leaf). Appendto (_c_select);
   //insert after
   _select.after (_c_select);
   //onchange
  }
  _c_select.change (picklistchange);



if (_rowvalue) {
_c_select.find ("[value=" +_rowvalue[_k]+ "]"). Prop ("selected", true);
_c_select.change ();
}
}
};






var lookup_new = function () {
 var lookup = $ (this);
 var Pre_script;
 if (pre_script = lookup.attr ("Pre_script")) {
  var ret = eval (pre_script);
  if (ret==false) {
   return false;
&NBSP;&NBSP}
 }
 var url = lookup.attr ("url");
 if (!url) {
  alert (' url not set ');
  return false;
 }
 var height = lookup.attr (' h ');
 if (!height) {
  height =;
&NBSP}
 var width = lookup.attr (' W ');
 if (!width) {
  width =;
&NBSP}
 window.open (URL, "Pselect", "scrollbars=yes,menubar=no,height=" +height+, width= "+width+", Resizable=yes,toolbar=no,location=no,status=no ");
 return false;
};



/**
* Lookup new value for hidden value
*/
var parent_lookup = function () {
var lookup = $ (this);
var pid = opener.$ ("#" + lookup.attr (' pid '));
if (!pid.length) {
Alert (lookup.attr (' pid ') + "not Found");
return false;
}
var pname = opener.$ ("#" + lookup.attr (' pname '));
if (!pname.length) {
Alert (lookup.attr (' pname ') + "not Found");
return false;
}



var aft_script;
Run current after script
if (Aft_script = lookup.attr (' aft_script ')) {
Window.eval (Aft_script);
}



Pid.val ($ (this). attr ("refID"));
Only operation to opener could trigger change event
Pid.change ();
Pname.val ($ (this). attr ("Refvalue"));
Pname.change ();
Parent After_script
if (Aft_script = pname.attr (' aft_script ')) {
Opener.window.eval (Aft_script);
}
if (Aft_script = pid.attr (' aft_script ')) {
Opener.window.eval (Aft_script);
}
Window.close ();
};



/**
* Default Upload Complete
*/
var uploadcomplete = function (event, ID, FileName, Responsejson) {
var uploadcomplete = function (e, data) {
To is replaced by jquery uploader
var _fileupload = $ (this);
Console.log (_fileupload);
Console.log (Data.result);
if (_fileupload.attr (' reload ')!=undefined) {
Window.location.reload ();
}
};



/**
* File upload function, the following to control action of upload
* ' endpoint ' as upload URL
* ' SID ' as session ID
* ' Complete ' optional to configure the custom upload complete function
*/
var genericupload = function (DOM) {
var Endpointurl = $ (this). attr (' endpoint ');
var sid = $ (this). attr ("Sid");
var completefunc = ' uploadcomplete ';
Setup custome Complete function
var Cuscomplete = $ (this). attr (' complete ');
if (cuscomplete) {
Completefunc = Cuscomplete;
}



$ (this). FileUpload ({
Url:endpointurl,
Autoupload:true,
DataType: ' JSON ',
FormData: [{' SessionID ': Sid}],
ParamName: ' Filedata ',
}). bind (' Fileuploaddone ', Window[completefunc]);
};



/**
* Matched errors with input
* Only matched errors could is identified here
*/
var advance_validate = function (errors, event) {
var conf = this.getconf ();
Loop errors
$.each (errors, function (index, error) {
Add error class into input Dom element
var input = Error.input;



Input.addclass (Conf.errorclass);



Get handle to the error container
var msg = Input.data ("Msg.el");



Create error data if not present, and add error class for input
' Msg.el ' data is linked to error message Dom Element
if (!msg) {
msg = $ (conf.message). addclass (Conf.messageclass). InsertAfter (input);
msg = $ (conf.message). addclass (Conf.messageclass). Appendto (Input.parent ());
Input.data ("Msg.el", msg);
}



Clear the Container
Msg.css ({visibility: ' hidden '}). Find ("span"). Remove ();



Populate messages
$.each (error.messages, function (i, m) {
$ ("<span/>"). HTML (M). Appendto (msg);
});



Make sure the ' width ' is ' not ' full body ' width so ' it can be positioned correctly
if (msg.outerwidth () = = Msg.parent (). Width ()) {
Msg.add (Msg.find ("span"));
}



Insert into correct position (relative to the field)



Msg.css ({visibility: ' visible '}). FadeIn (Conf.speed);
Msg.parent (). addclass ("Colerror");
});
};



var advance_inputs = function (inputs) {
 var conf = this.getconf ()     
  Inputs.removeclass (Conf.errorclass). each (the function () {
   var msg = $ (this). Data ("Msg.el");
   if (msg) {
   msg.hide ();
   msg.parent (). Removeclass ("Colerror");
   }
   });
 if ($ (". Colerror"). Size () = 0) { 
  var form = $ (this);
  var errhint = Form.find (". Formerror").
  if (errhint.size () = = 0) {
   errhint = $ ("#pageError");
   errhint.text ("). Hide ();
  }
 }
};



/**
* When refname are contained to be selected
*/
var checkall = function () {
var check = $ (this);
var refname = check.attr (' refname ');
if (refname) {
if (Check.prop ("checked")) {
$ ("input[name*= '" +refname+ "]"). Prop ("checked", true);
}else{
$ ("input[name*= '" +refname+ "]"). Prop ("checked", false);
}
}



var refclass = check.attr (' Refclass ');
if (Refclass) {
if (Check.prop ("checked")) {
$ ("input." +refclass). Prop ("checked", true);
}else{
$ ("input." +refclass). Prop ("checked", false);
}
}
};



/**
* Setup readonly checkbox
*/
var Readonlycheck = function (e) {
E.preventdefault ();
return false;
};



/**
* Select List Disable
*/
var readonlyselect = function () {
$ (this). Prop ("Disabled", true);
};





$ (document). Ready (function () {


$ (document). Ajaxstart (function () {


Clean up the Ajax request Page level Error


$ ("#pageError"). Text ('). Hide ();


Clean up teh Form Error


$ (". Formerror"). Text ('). Hide ();


Blocking All AJAX Processing


if (ajaxsynchronized) {


$.blockui ({message: "{__ (' l_processing ')}"});


}


});


$ (document). Ajaxstop (function () {


if (ajaxsynchronized) {


if ($ (window). Data (' blockui.isblocked ') = = 1) {


if (Ajaxautounblock) {


$.unblockui ();


}else{


Ajaxautounblock = true;


}


}


}else{//change back to default Synchronized mode from Async


Ajaxautounblock = true;


Ajaxsynchronized = true;


}


});


$ (document). Ajaxerror (function (event, request, settings) {


Alert (' Ajax Request error! Url= ' +settings.url);


if (ajaxsynchronized) {


if ($ (window). Data (' blockui.isblocked ') = = 1) {


if (Ajaxautounblock) {


$.unblockui ();


}else{


Ajaxautounblock = true;


}


}


}else{


Ajaxautounblock = true;


Ajaxsynchronized = true;


}


});


Force Unblockui
$ (document). Click (function () {
if ($ (window). Data (' blockui.isblocked ') = = 1) {
$.unblockui ();
var Returi = $ (window). Data (' Blockui.returi ');
if (Returi) {
window.location = Returi;
}
}});



$.tools.validator.addeffect ("Advanced", advance_validate,advance_inputs);
$.tools.validator.fn ("[Data-equals]", {"{lang}": "{__ (' e_notequal ')}"}, Data_equals_validate);
$.tools.validator.fn ("[Hidden-id]", validate_hidden_id);



$ (". Ajax_form_post"). Validator ({lang: ' {lang} ', Effect: ' Advanced '}). Submit (Ajax_form_post);
$ (". Ajax_form_post"). each (Ajax_post_form_hidden);
$ (". Spin_number"). each (Spin_number);
$ (". Date_input"). each (date_input);
$ (". Time_picker"). each (Time_picker);



$ ('. Ajax_link_req '). Click (ajax_link_req);
Client validation for the hidden ID
$ (". Require_validate"). Validator ({lang: ' {lang} ', Effect: ' Advanced '});



  $ (". Btn_nav"). Click (Btn_nav);
  $ (". Btn_req"). Click (btn_req);
  $ ("Button.btn_action"). Click (Ajax_action_button);
  $ (". Lookup_new"). Click (lookup_new);
  $ (". Parent_lookup"). Click (parent_lookup);
  $ (". Ajax_checkbox"). Click (Ajax_checkbox);
  $ (". Bool_checkbox"). Click (Bool_checkbox);
  $ (". Checkall"). Click (Checkall);
  $ ("Img[rel]"). Overlay ();
     $ ("Input[tip]"). ToolTip ({position: "Center Right"});



At the last we'll do localize
$.tools.validator.localize ("{lang}", {
' * ': ' {__ (' E_all ')} ',
': Email ': ' {__ (' E_email ')} ',
': Number ': ' {__ (' E_decimal ')} ',
': url ': ' {__ (' E_url ')} ',
' [Max] ': {__ (' e_max_length ')} ',
' [min] ': ' {__ (' e_min_length ')} ',
' [Required] ': {__ (' E_not_empty ')} ',
});
});





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.