webpart form submit to custom list in sharepoint - 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>

Related

SharePoint - How to show ALL radio button choices on display form?

I have recently created a sharepoint list that has a multitude of radio button choices. When the user creates a new entry, they pick a radio button and submit. However, when they view using the display form, only the choice that they selected appears. I want to make it so that ALL of the possible choices appear, but it still shows what they have picked. Is there any possible way of doing this?
This is what appears currently
This is what I want (and what users see when they submit a new item)
We can use REST API to get all the filed choices and then append the HTML to the field in the display form using jQuery. The following code for your reference. Add the code into a script editor web part in the dispform.aspx page.
<script src="//code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var fieldTitle="AP Coding/Slip Claim Forms*/Limited Purchase Order";
var currentFieldValue=$("h3.ms-standardheader:contains('"+fieldTitle+"')").parent().next()[0].innerText.trim();
var fieldHTML=GetFieldChoices(currentFieldValue,fieldTitle);
$("h3.ms-standardheader:contains('"+fieldTitle+"')").parent().next().html(fieldHTML);
});
function GetFieldChoices(currentFieldValue,fieldTitle){
var listId = _spPageContextInfo.pageListId.replace("{","").replace("}","");
var fieldHTML="";
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists(guid'"+listId+"')/fields?$select=Choices&$filter= Title eq '"+fieldTitle+"'";
$.ajax({
url: url,
method: "GET",
async:false,
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var choices = data.d.results[0].Choices.results;
$.each(choices,function(index,choice){
if(choice==currentFieldValue){
fieldHTML+="<input type='radio' disabled='disabled' checked='checked' name='"+fieldTitle+"' value='"+choice+"'>"+choice;
}else{
fieldHTML+="<input type='radio' disabled='disabled' name='"+fieldTitle+"' value='"+choice+"'>"+choice;
}
if(index<choices.length){
fieldHTML+="<br>";
}
});
},
error: function (error) {
console.log(JSON.stringify(error));
}
});
return fieldHTML;
}
</script>

Sharepoint survey: Dynamically update lookup

I currently am working on designing a Sharepoint survey.
The first question is a lookup from a list, which looks like this:
Course1
Course2
Course3
Course4
Now, the user has to select one of these answers. While I got the lookup working, I have problem in updating the list.
the idea is, that the user can add his own courses to complement the list.
So for example, he can select OTHER and type in Course5 into a textbox, which should then be added to the list. The next user should then be able to select Course5 from the drop down list.¨
I have problems writing the result of a survey into the list - is this even possible?
Kind regards.
In choice field, it provide the 'fill-in' feature, unfortunately, the lookup column can't provide this feature.
As a workaround, we can using jQuery append a textbox and a button in the lookup column below in the newform.aspx page. Add some text in the textbox and click the "Add" button, then add data to the lookup list. The following example for your reference:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
var questionTitle="question1";
var lookupListName="CL30";
$(function(){
$("select[title='"+questionTitle+"']").closest("td").append("<input id='lookupitemTitle' type='text'/> <input id='addlookupitembtn' type='button' value='Add'>");
$("#addlookupitembtn").click(function(){
if($("#lookupitemTitle").val().trim()!=""){
AddListItem(lookupListName);
}
});
});
function AddListItem(listName){
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": { "type": itemType },
"Title": $("#lookupitemTitle").val()
};
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_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) {
var item=data.d;
$("select[title='"+questionTitle+"']").append("<option selected='selected' value='"+item.ID+"'>"+item.Title+"</option>");
},
error: function (data) {
alert("Error");
}
});
}
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>

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

jQuery validation engine using the “ajax[selector]”

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?

Data validation in server by socket.io and node.js then POST a from

I have a form like this:
<form method='post' action='next' onsubmit="return validateMyForm();" >
<input type="text" id="data" />
<input type="submit" />
<p id="result"></p>
and this code for interact with node.js:
socket = io.connect();
function vlidateMyForm(){
var data = $('data').val();
socket.emit('login',{data: data}); // check dataBase in server
return false;
}
socket.on('responseLogin',function(result){
if(result){ // if data is valid
// submit form
}
else{ // data invalid
$('#result').html('field is not valid')
}
});
I want to submit my form, when the result is true. What should I do to solve this problem?
Change socket.on('responseLogin',function(result){... to socket.on('login',function(result){... should fix your problem
You can use Jquery submit to submit the form :
$("form#formID").submit();
Your form must have action attribute like action='url_to_post_to' for this.
Or if you like to use AJAX so that you can process the data, you can do :
$.ajax({
type: "POST",
url: 'url_to_post_to',
data: $("#formID").serialize(),
success: function(data)
{
alert(data);
}
});

Resources