jQuery validation engine using the “ajax[selector]” - jquery-validation-engine

I have the following (multistep form) HTML:
<form id="myform">
<fieldset id="first_step">
<input type="text" name="register" placeholder="Αρ. Μητρώου" id="register" class="validate[required,custom[integer]]" />
<input type="text" name="email" placeholder="Πόλη" id="city" class="validate[required,ajax[email]]" />
<input type="button" name="next" class="next action-button" value="Επόμενο" id="next1" />
</fieldset>
<fieldset id="second_step">
....
....
....
</fieldset>
</form>
The instantiation js code plus logic (myform.js)
$(document).ready(function(){
var first_step = $("#first_step");
var second_step = $("#second_step");
$("#myform").validationEngine('attach', {
promptPosition : "centerRight",
scroll: false
});
$("#next1").on('click', function (e) {
e.preventDefault();
var valid = $("#myform").validationEngine('validate');
if (valid == true) {
second_step.show();
} else {
$("#ithemiscustomerform").validationEngine();
}
});
});
The rules “validationEngine-el.js”
(function($){
$.fn.validationEngineLanguage = function(){
};
$.validationEngineLanguage = {
newLang: function(){
$.validationEngineLanguage.allRules = {
"required": { // Add your regex rules here, you can take telephone as an example
"regex": "none",
"alertText": "* Υποχρεωτικό πεδίο",
"alertTextCheckboxMultiple": "* Παρακαλώ επιλέξτε",
"alertTextCheckboxe": "* Υποχρεωτικό πεδίο",
"alertTextDateRange": "* Και τα δύο πεδία ημ/νίας είναι υποχρεωτικά"
},
// --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
"email": {
"url": "http://localhost/userformServer/validator.cfc?method=valEmail",
// you may want to pass extra data on the ajax call
//"extraData": "name=eric",
"alertText": "* Μη έγκυρο email",
"alertTextLoad": "* Παρακαλώ περιμένετε...",
"alertTextOk": "* Το eimail είναι διαθέσιμο"
},
"integer": {
"regex": /^[\-\+]?\d+$/,
"alertText": "* Μη έγκυρος ακέραιος"
}
};
}
};
$.validationEngineLanguage.newLang();
})(jQuery);
The problem
Remote validation works great for the “email” field “on blur” –while user completing the form. But when I click the “next1” button to move on the next fieldset (“second_step”) even if the email field is valid (remotely valid) the form doesn’t move to the next fieldset (see “myform.js” onclick). Specifically when I call “$("#myform").validationEngine('validate');” inside the click event it returns false. I think this occurs due the asynchronous nature of validation. Is there any workaround for this?

Related

Uncaught TypeError: Cannot read property 'checked' of null from chrome.storage.get()

When I try to load my Google Chrome extension into the browser, I get the above error for my options.js file:
Here are my options.js:
var email_addr = document.getElementById("email_addr");
var email_password = document.getElementById("email_password");
var registerButton = document.getElementById("register");
var url = document.getElementById("url");
var port = document.getElementById("port");
var password = document.getElementById("password");
var ecs_mode = document.getElementById("ecs_mode");
var encrypt = document.getElementById("encrypt");
var include_content = document.getElementById("include_content");
var saveButton = document.getElementById("save");
debugger;
restore_settings();
chrome.storage.sync.get({"emailAddr": email_addr.value,
"emailPassword": email_password.value,
"contentServerURL": url.value,
"contentServerPort": port.value,
"contentServerPassword": password.value,
"ecs_mode": ecs_mode.checked,
"encrypt": encrypt.checked,
"include_content": include_content.checked},
function() {
// Update status to let user know settings were saved.
var status = document.getElementById("status");
status.innerHTML = "Settings Saved.";
setTimeout(function() {
status.innerHTML = "";
}, 750);
});
function register_addr() {
}
// Saves settings to chrome.storage.
function save_settings() {
if (!password.value) return;
chrome.storage.sync.set({"emailAddr": email_addr.value,
"emailPassword": email_password.value,
"contentServerURL": url.value,
"contentServerPort": port.value,
"contentServerPassword": password.value,
"ecs_mode": ecs_mode.checked,
"encrypt": encrypt.checked,
"include_content": include_content.checked},
function() {
// Update status to let user know settings were saved.
var status = document.getElementById("status");
status.innerHTML = "Settings Saved.";
setTimeout(function() {
status.innerHTML = "";
}, 750);
});
}
// Restores select box state to saved value from localStorage.
function restore_settings() {
chrome.storage.sync.get("emailAddr", function(val) {
email_addr.value = val.emailAddr;
});
chrome.storage.sync.get("emailPassword", function(val) {
email_password.value = val.emailPassword;
});
chrome.storage.sync.get("contentServerPassword", function(val) {
password.value = val.contentServerPassword;
});
chrome.storage.sync.get("contentServerURL", function(val) {
url.value = val.contentServerURL;
});
chrome.storage.sync.get("contentServerPort", function(val) {
port.value = val.contentServerPort;
});
chrome.storage.sync.get("ecs_mode", function(val) {
ecs_mode.checked = val.ecs_mode;
});
chrome.storage.sync.get("encrypt", function(val) {
encrypt.checked = val.encrypt;
});
chrome.storage.sync.get("include_content", function(val) {
include_content.checked = val.include_content;
});
registerButton.disabled = false;
saveButton.disabled = false;
}
function ecs_mode_fn() {
if (ecs_mode.checked) {
encrypt.disabled = false;
include_content.disabled = false;
}
else {
encrypt.disabled = true;
include_content.disabled = true;
}
}
function toggleButton() {
if (email_addr.value.length == 0) {
registerButton.disabled = true;
saveButton.disabled = true;
}
else {
registerButton.disabled = false;
saveButton.disabled = false;
}
}
document.addEventListener('DOMContentReady', restore_settings);
if (document.querySelector('#save, #ecs_mode, #save, #restore, #register') != null) {
document.querySelector('#ecs_mode').addEventListener('click', ecs_mode_fn);
document.querySelector('#save').addEventListener('click', save_settings);
document.querySelector('#restore').addEventListener('click', restore_settings);
document.querySelector('#email_addr').addEventListener('keyup', toggleButton);
document.querySelector('#register').addEventListener('click', register_addr);
}
options.html:
<html>
<head><title>ECS Extension Settings</title>
<style type="text/css">
body {
width: 800px;
height: 200px;
}
</style>
</head>
<body>
<center><h1>ECS Content Server Settings</h1></center>
<div title="Enter your e-mail address and password here. The address can be a regular Gmail address ('<someone>#gmail.com') or an e-mail address associated with a Google business account.">
<b>Your e-mail address:</b>
<input type="text" id="email_addr">
<b>Password:</b>
<input type="password" id="email_password">
<button id="register" disabled>Register</button>
</div>
<br>
After entering your e-mail address and password, press the <b>Register</b> button to register your address with the ChiaraMail content server. You will then be sent a registration confirmation e-mail containing a link. Select the link to show your content server password and enter the password in the <b>Content server password</b> field below.
<p>
<div title="The name and port number of the content server are fixed. Enter the password you were assigned during registration. You may change your password later at https://www.chiaramail.com/login.jsp">
<b>Content server URL:</b>
<input type="text" id="url" value="www.chiaramail.com" disabled>
<b>Content server port:</b>
<input type="text" id="port" value="443" size="4" disabled>
<b>Content server password:</b>
<input type="password" id="password" maxlength="8" size="8">
<p>
</div>
<div title="Check the 'Send as ECS' box if you want to send e-mail by default using the ECS technology. You will have the option of changing this setting when you compose your message.">
<b>Send as ECS: </b>
<input type="checkbox" id="ecs_mode" checked>
</div>
<div title="Check the 'Encrypt message' box if you want the message to be stored encrypted on the content server. You will have the option of changing this setting when you compose your message.">
<b>Encrypt message: </b>
<input type="checkbox" id="encrypt">
</div>
<div title="Check the 'Include content' box if you want the message content to be sent along with the mail headers (useful when sending to mixed recipients, some enabled for ECS and others who are not). You will have the option of changing this setting when you compose your message.">
<b>Include content: </b>
<input type="checkbox" id="include_content" checked>
</div>
<!--<div title="Select the 'Show ECS users' box to display message senders in magenta if the sender's e-mail address is registered with the ChiaraMail content server. This enables you to know which of your recipients are able to read ECS messages, but setting this option may adversely affect performance.">
<p>
<b>Show ECS users:</b>
<input type="checkbox" id="ecsusers" checked>-->
</div>
<br>
<div id="status"></div>
<div title="Press 'Save settings' to save your settings and 'Restore settings' to display them. Changes made to your account are propagated to all your devices and systems.">
<button id="save" disabled>Save settings</button>
<button id="restore">Restore settings</button>
</div>
<script src="options.js"></script>
</body>
</html>
and manifest.json:
"name": "Envelope-Content Splitting (ECS) Support for Gmail",
"version": "1.0",
"manifest_version": 2,
"description": "Add ECS support for Gmail running in Chrome. This enables Gmail users who access their accounts via the Google Chrome browser to send and read ECS mail. Check out http://www.chiaramail.com for information about ECS and for links to other FREE ECS-enabled mail clients and extensions.",
"browser_action": {
"default_icon": {"19": "ecs_icon_19.png", "38": "ecs_icon_38.png"},
"default_title": "Press here to configure ECS settings",
"default_popup": "options.html"
},
"options_page": "options.html",
"icons": { "16": "ecs_icon_16.png", "48": "ecs_icon_48.png", "128": "ecs_icon_128.png"},
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"run_at": "document_idle",
"matches": ["https://mail.google.com/mail/*"],
"js": ["updateContent.js", "colorHeaders.js", "renderContent.js", "sendOptions.js", "base64.js", "jsaes.js"]
}
],
"permissions": ["tabs",
"activeTab",
"storage",
"https://mail.google.com/mail/*"],
"content_security_policy": "script-src 'self' https://www.chiaramail.com; object-src 'self'"
}
I suspect the problem is with the way I coded chrome.storage.get(), but I couldn't find the API reference, only an example of how to call it. I'm pretty sure I coded the call to chrome.storage.get() correctly, though. What am I missing?
It turns out that I needed to clear the errors after correcting a missing UI element. I don't understand why Google requires users to clear the errors before reloading the extension; the reload should clear them.

Ajax status 0, success not firing, no info with the errors thrown

I'm working on an app where the user enters info into a form, the form passes the info to my route, the route passes the info to the db, and then when done, it's supposed to update the page accordingly.
The issues I am having is that when you hit submit, the info does land on the database and gets saved but then on the callback/success/complete part of ajax, they dont fire and you have to hit a manual reload for the info to show up. I'm going to assume that this is because of the readystate of 0.
I've tried many solutions other people here on SO have gotten but to no avail.
Here is my code.
HTML:
<div id="createTodoFormW">
<form method="post" id="createTodoForm">
<input type="text" name="todoCompanyName" id="todoCompanyName" placeholder="Enter a Company name or leave empty if its a personal ToDo "><br>
<input type="text" name="todoTitle" id="todoTitle" placeholder="Enter a Title for this note"><br>
<input type="text" name="todoIsFor" id="todoIsFor" placeholder="Who is this ToDo for? ( If left empty, ToDo will be assigned to [ YOU ] )"><br>
<input type="hidden" name="todoPostedBy" id="todoPostedBy" value="LOGGED IN USER HERE">
<input type="hidden" name="todoCompleted" id="todoCompleted" value="no">
<input type="text" name="todoFirstMessage" id="todoFirstMessage" placeholder="Enter your ToDo message"><br>
<select name="todoPriority" id="todoPriority">
<option id="todoPriorityDefaultSelected" >Please select your ToDo priority</option>
<option id="todoPrioritySelected" selected>green</option>
<option id="todoPrioritySelected">yellow</option>
<option id="todoPrioritySelected">red</option>
</select><br>
<input type="submit">
</form>
</div><!-- createTodoFormW ender -->
express/node route:
app.post("/notesapi", (request, response) =>{
//mongoose.connect(databaseLoc);
const newNoteToAdd = new NotesModel({
todoCompany : request.body.todoCompany,
todoIsFor : request.body.todoIsFor,
todoPostedBy : request.body.todoPostedBy,
todoCompleted : request.body.todoCompleted,
todoPriority : request.body.todoPriority,
todoMessages : request.body.todoMessages,
todoTitle : request.body.todoTitle,
todoDate : currDate
});
newNoteToAdd.save((err, data)=>{
if(err){
console.log("There was an error uploading your data " + err);
}else{
//mongoose.connection.close();
console.log("Data upload success.");
}
});
});
front end js:
$("#createTodoForm").submit(function(evt){
evt.preventDefault();
$.ajax({
type : "POST",
cache : false,
dataType : "json",
contentType : "application/json; charset=utf-8",
url : "/notesapi",
data : JSON.stringify({
todoCompany : $("#todoCompanyName").val(),
todoTitle : $("#todoTitle").val(),
todoPostedBy : $("#todoPostedBy").val(),
todoIsFor : $("#todoIsFor").val(),
todoMessages : $("#todoFirstMessage").val(),
todoPriority : $("#todoPriority").val(),
todoCompleted : false
}),
success : function(){
console.log("did ajax fire and comlete?");
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.readyState == 4) {
console.log("HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText");
}
else if (XMLHttpRequest.readyState == 0) {
console.log("Network error (i.e. connection refused, access denied due to CORS, etc.");
console.log(textStatus);
console.log(errorThrown)
console.log(XMLHttpRequest.readyState);
}
else {
console.log("something weird is happening");
}
}
}); //ajax end
});
I need help. Been on this for days and cant figure it out. The main question i guess is, where is this state coming from and why doesnt my success function run?
thanks in advance for any assistance given.

Dgrid + Selection Issue

Still trying to work with Dgrid (0.4) and dojo (1.10), I have now another issue with the selection.
My web page contain a Dialog opened when you click on a button.
Inside this dialog, we have the following code which display a grid with data coming from a database through a Json HTTP page. This is working fine, even sorting and query filtering.
What I want to do know is to allow the user to double click on a row, get the selected row Id contains in the first column to update the form in the main page. I use the dgrid/selection for this. However, it always return the last row of the grid instead of the one the user selected.
The selection code is based on this :
http://dgrid.io/tutorials/0.4/hello_dgrid/
Any idea?
Thanks
<script language="javascript">
require
(
[
"dojo/_base/declare",
"dojo/_base/array",
"dgrid/OnDemandList",
"dgrid/OnDemandGrid",
"dgrid/Keyboard",
"dgrid/Selection",
"dgrid/Editor",
"dgrid/extensions/ColumnHider",
"dstore/Memory",
"dstore/RequestMemory",
"dojo/_base/lang",
"dojo/dom-construct",
"dojo/dom",
"dojo/on",
"dojo/when",
"dojo/query",
"dojo/store/Observable",
"dstore/Rest",
"dojo/_base/Deferred",
"dojo/store/Cache",
"dojo/domReady!",
],
function(
declare, arrayUtil, OnDemandList, OnDemandGrid, Keyboard, Selection, Editor, ColumnHider, Memory, RequestMemory, lang, ObjectStore, dom, on, when, query, Observable, Rest, Deferred
){
var fform = dom.byId("filterForm");
var ContactColumns = [
{ label: "", field: "contact_id", hidden: true, unhidable: true},
{ label: "Company Name", field: "company_name", unhidable: true },
{ label: "Contact Name", field: "contact_name", unhidable: true },
{ label: "Email", field: "contact_email", unhidable: true }
];
var ContactGrid=declare([OnDemandGrid, Keyboard, Selection,ColumnHider]);
var contactlist = new Observable(new Rest({ target: './ajax.contactsLoader.php' }));
var selection = [];
window.contactgrid = new ContactGrid(
{
className: "dgrid-selectors",
collection: contactlist,
maxRowsPerPage:10,
selectionMode: 'single',
cellNavigation: false,
columns: ContactColumns
}, "contacttable"
);
on(fform, "submit", function (event) {
var cpy_filter = fform.elements.fcompany_name.value;
var ct_filter = fform.elements.fcontact_name.value;
var email_filter = fform.elements.fcontact_email.value;
contactgrid.set('collection',contactlist.filter({contact_name: ct_filter, company_name: cpy_filter, contact_email: email_filter }));
contactgrid.refresh();
event.preventDefault();
});
contactgrid.on('dgrid-select', function (event) {
// Report the item from the selected row to the console.
console.log('Row selected: ', event.rows[0].data);
});
contactgrid.on('dgrid-deselect', function (event) {
console.log('Row de-selected: ', event.rows[0].data);
});
contactgrid.on('.dgrid-row:click', function (event) {
var row = contactgrid.row(event);
console.log('Row clicked:', row.data);
});
}
);
</script>
<div class="dijitDialogPaneContentArea" style="width:96%;margin-left:5px">
<form id="filterForm">
<div class="dijitDialogPaneActionBar" >
<button data-dojo-type="dijit.form.Button" type="submit">Filter</button>
<button
data-dojo-type="dijit.form.Button"
data-dojo-attach-point="submitButton"
type="submit"
>
Select
</button>
<button
data-dojo-type="dijit.form.Button"
data-dojo-attach-point="cancelButton"
>
Close
</button>
</div>
<div data-dojo-attach-point="contentNode" >
<input type="text" data-dojo-type="dijit.form.TextBox" name="fcompany_name" id="fcompany_name" style="width:33%">
<input type="text" data-dojo-type="dijit.form.TextBox" name="fcontact_name" id="fcontact_name" style="width:32%">
<input type="text" data-dojo-type="dijit.form.TextBox" name="fcontact_email" id="fcontact_email" style="width:33%">
<div id="contacttable">
</div>
</div>
</form>
</div>
Just found the reason.
the columns need to have a 'id' column called ID. I just change the 'contact_id' column to 'id' and it works fine.
thanks

Unobtrusive validation with Jquery Steps Wizard

Recently I asked a question for how to customize the JQuery Steps as I wanted to use partial views instead of static content. I have partially solved that problem by using the following code supported by jquery-steps,
<h3>Step 1</h3>
<section data-mode="async" data-url="/Formation/RenderStep1"></section>
<h3>Step 2</h3>
<section data-mode="async" data-url="/Formation/RenderStep2"></section>
Now the big problem I am facing right now is how to use unobtrusive validation. I don't want to use JQuery custom validation and there must be some way of using Obtrusive with it.
Each partial view that is rendered has its own form. I want to validate the form in the onStepChanging function of jquery-steps,
$("#my-steps").steps({
headerTag: "h3",
bodyTag: "section",
contentMode: "async",
transitionEffect: "fade",
stepsOrientation: "vertical",
onStepChanging: function (event, currentIndex, newIndex) {
return true;
}
});
I have tried calling $.validator.unobtrusvie.parse('#myform'); in the onStepChanging function but ('#myform') is undefined and still I don't know that whether this is the right way to call the unobtrusive validation manually. Kindly guide me and show me the direction to achieve this. Any help will be highly appreciated.
It sounds like your trying manage multiple forms within the JQuery Steps library and I don't think that is what its intended for.
When you configure JQuery Steps, you set it up against the form in your view.
Unobtrusive JQuery Validation is looking at the model in your view and automatically configuring the HTML with the relevant data attributes for error handling.
This validation should be firing at the client side automatically.
There shouldn't be a problem with using Partial View's, as long as there encapsulated within the same form element.
What is the requirement to have each partial view wrapped in its own form? If your trying to make multiple posts throughout the JQuery Steps form wizard, your defeating the object.
At each step in the JQuery Steps form, your only validating the one form like this :-
onStepChanging: function (event, currentIndex, newIndex) {
//Allways allow user to move backwards.
if (currentIndex > newIndex) {
return true;
}
// Remove the validation errors from the next step, incase user has previously visited it.
var form = $(this);
if (currentIndex < newIndex) {
// remove error styles
$(".body:eq(" + newIndex + ") label.error", form).remove();
$(".body:eq(" + newIndex + ") .error", form).removeClass("error");
}
//disable validation on fields that are disabled or hidden.
form.validate().settings.ignore = ":disabled,:hidden";
return form.valid();
}
Once the user has finished entering data, and the client side validation has been met, you hook into the onFinished method and post the form :-
onFinished: function (event, currentIndex) {
var form = $(this);
form.submit();
}
The purpose of JQuery Steps is to allow the user to have a fluid experience of filling out a form and to not be overwhelmed with the number of questions been asked.
From the developers perspective, it enables us to split up the form into nice size-able chunks without having to worry about saving progress between screens or losing the state of the form data and allows us to capture all of the required data with only having to make that one post once all validation criteria has been met.
I tried the formvalidation plugin, it will relax your mind from searching in validation without form tag or validation without submit the form that's the issue I solved when I tried it.
I know it's not free but you can try it from here, personally I like it
First update height after validation
<style type="text/css">
/* Adjust the height of section */
#profileForm .content {
min-height: 100px;
}
#profileForm .content > .body {
width: 100%;
height: auto;
padding: 15px;
position: relative;
}
Second, add data-steps index to your section*
<form id="profileForm" method="post" class="form-horizontal">
<h2>Account</h2>
<section data-step="0">
<div class="form-group">
<label class="col-xs-3 control-label">Username</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="username" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Email</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="email" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Password</label>
<div class="col-xs-5">
<input type="password" class="form-control" name="password" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Retype password</label>
<div class="col-xs-5">
<input type="password" class="form-control" name="confirmPassword" />
</div>
</div>
</section>
Third, javascript code
<script>
## // to adjust step height to fit frame after showing validation messages##
$(document).ready(function() {
function adjustIframeHeight() {
var $body = $('body'),
$iframe = $body.data('iframe.fv');
if ($iframe) {
// Adjust the height of iframe
$iframe.height($body.height());
}
}
// IMPORTANT: You must call .steps() before calling .formValidation()
$('#profileForm')
// setps setup
.steps({
headerTag: 'h2',
bodyTag: 'section',
onStepChanged: function(e, currentIndex, priorIndex) {
// You don't need to care about it
// It is for the specific demo
adjustIframeHeight();
},
// Triggered when clicking the Previous/Next buttons
// to apply validation to your section
onStepChanging: function(e, currentIndex, newIndex) {
var fv = $('#profileForm').data('formValidation'), // FormValidation instance
// The current step container
$container = $('#profileForm').find('section[data-step="' + currentIndex +'"]');
// Validate the container
fv.validateContainer($container);
var isValidStep = fv.isValidContainer($container);
if (isValidStep === false || isValidStep === null) {
// Do not jump to the next step
return false;
}
return true;
},
// Triggered when clicking the Finish button
onFinishing: function(e, currentIndex) {
var fv = $('#profileForm').data('formValidation'),
$container = $('#profileForm').find('section[data-step="' + currentIndex +'"]');
// Validate the last step container
fv.validateContainer($container);
var isValidStep = fv.isValidContainer($container);
if (isValidStep === false || isValidStep === null) {
return false;
}
return true;
},
onFinished: function(e, currentIndex) {
// Uncomment the following line to submit the form using the defaultSubmit() method
// $('#profileForm').formValidation('defaultSubmit');
// For testing purpose
$('#welcomeModal').modal();
}
})
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
// This option will not ignore invisible fields which belong to inactive panels
excluded: ':disabled',
fields: {
username: {
validators: {
notEmpty: {
// for asp.net i used element attribute to integerated with unobtrusive validation
// message :$('username').attr('data-val-required')
message: 'The username is required'
},
stringLength: {
min: 6,
max: 30,
message: 'The username must be more than 6 and less than 30 characters long'
},
regexp: {
regexp: /^[a-zA-Z0-9_\.]+$/,
message: 'The username can only consist of alphabetical, number, dot and underscore'
}
}
},
email: {
validators: {
notEmpty: {
message: 'The email address is required'
},
emailAddress: {
message: 'The input is not a valid email address'
}
}
},
password: {
validators: {
notEmpty: {
message: 'The password is required'
},
different: {
field: 'username',
message: 'The password cannot be the same as username'
}
}
},
confirmPassword: {
validators: {
notEmpty: {
message: 'The confirm password is required'
},
identical: {
field: 'password',
message: 'The confirm password must be the same as original one'
}
}
}
}
});

webpart form submit to custom list in sharepoint

Is it possible to create a form visual webpart with fields like name, email, address and submit button. After user submit data should be submitted to sharepoint custom list here custom list will have same fields like name, email, address. I created one custom list.
I search on internet but i didn't find any solutions for that. Also am new to sharepoint. If any one can provide some links it will be helpful.
Thanks
Yes, this is very possible using jQuery and AJAX.
So, lets say that, just to be brief, this is your input:
<input type='text' id='name' />
<input type='submit' id='submitdata' value='submit />
Using jquery, you would do this:
$(function(){
$('#submitdata').click(function(){
//this gets the value from your name input
var name = $('#name').val();
var list = "PutYourListNameHere";
addListItem(name, list);
});
});
function addListItem(name, listname) {
var listType = "PutTheTypeOfListHere";
// Prepping our update & building the data object.
// Template: "nameOfField" : "dataToPutInField"
var item = {
"__metadata": { "type": listType},
"name": name
}
// Executing our add
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
console.log("Success!");
console.log(data); // Returns the newly created list item information
},
error: function (data) {
console.log("Error!");
console.log(data);
}
});
}
This SHOULD work. I am not at work where my SharePoint station is, so if you are still having issues with this, let me know.
You may use SPServices also, It will work
<script type="text/javascript" src="~/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="~/jquery.SPServices-0.7.2.min.js"></script>
HTML
<input type='text' id='name' />
<input type='text' id='email' />
<input type='text' id='mobile' />
<input type='submit' id='submit' value='Submit' />
SPServices
<script type="text/javascript">
$("#submit").click(function(){
var Fname=$("#name").val();
var Email =$("#email").val();
var Mobile =$("#mobile").val();
$().SPServices({
operation: "UpdateListItems",
async: false,
batchCmd: "New",
listName: "YourCustomListName",
valuepairs: [["Fname", Fname], ["Email", Email], ["Mobile", Mobile]], //"Fname","EMail" and "Mobile" are Fields Name of your custom list
completefunc: function(xData, status) {
if (status == "success") {
alert ("Thank you for your inquiry!" );
}
else {
alert ("Unable to submit your request at this time.");
}
}
});
});
</script>

Resources