Sharepoint survey: Dynamically update lookup - sharepoint

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>

Related

How to prevent tabulator input to close when clicking elsewhere

I have a custom datepicker calendar I want to show for editing dates in tabulator. I have managed to open the calendar when the row cell is click by providing a custom editor.
The problem is that as soon as I click on my calendar, (what I think happens) is that Tabulator´s "As a fallback Tabulator will cancel the edit if an editor is blured and the event has not been correctly handled." behavior triggers before I can process the click on my calendar and update the cell value.
Is there a way to allow the user to click on the calendar without making tabulator cancel the edit?
Don't know which custom date picker you are using but here is a working example using flatpickr:
let initialTableData = [{
eventName: "Christmas party",
eventDate: "12-25-2021"
},
{
eventName: "New Years party",
eventDate: "12-31-2021"
}
]
function dateEditor(cell, onRendered, success, cancel, editorParams) {
let editor = document.createElement("input")
editor.value = cell.getValue()
let datepicker = flatpickr(editor, {
dateFormat: "m-d-Y",
onChange: setDate,
onClose: setDate
})
function setDate(selectedDates, dateStr, instance) {
success(dateStr)
instance.destroy()
}
onRendered(() => {
editor.focus()
})
return editor
}
let eventTable = new Tabulator("#eventTable", {
data: initialTableData,
columns: [{
title: "Event",
field: "eventName",
width: 200
},
{
title: "Event Date",
field: "eventDate",
editor: dateEditor
}
]
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/tabulator/5.0.7/js/tabulator.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.9/flatpickr.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/tabulator/5.0.7/css/tabulator.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet" />
<div id="eventTable"></div>
Here is the CodePen

Render a mixin Pug template

I want to render a template after a Ajax call.
My code is:
index.pug
include form.pug
+list('style')
form.pug
mixin list(style)
p(class=style) my form
I want to add form.pug after click a button, so
my ajax call is:
$.ajax({
url: "/myroute",
method: "POST",
data: msgObj,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
datatype: "json",
success: function (msg) {
div.prepend(msg.template)
},
});
/myroute (server-node) is:
const pug = require('pug');
var template = pug.renderFile('Path/form.pug');
res.send({"template":template,"style":"new_style"});
My template doesn't appear after click the button.
In I remove mixin, everything works, but I need pass a param during the template generation
Call the mixin somewhere in the page, select it in the DOM after AJAX call and fill the needed values before prepending it.

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>

Setting default values with selectize api for listbox in selectize.js

I am trying to set default value upon page load in a dropdown listbox which loads value thru an ajax call. Not able to set values using setValue method as suggested in the docs. Please help. Following are code snippets from the project
HTML
<select name="country" placeholder="Please Select Country ..."></select>
Data population JS code
$('[name="country"]').selectize({
valueField: 'name',
labelField: 'name',
searchField: 'name',
preload: true,
create: false,
render: {
option: function(item, escape) {
return '<div>' + escape(item['name']) + '</div>';
}
},
load: function(query, callback) {
$.ajax({
url: '/countrydata',
type: 'GET',
error: function() {
callback();
},
success: function(res) {
callback(res);
}
});
},
});
Default Value Setting Code
$('[name="country"]').selectize();
$('[name="country"]')[0].selectize.setValue("Japan");
Is there a hack where I can circumvent the problem ? I am been trying to get this work for couple of days now.
Thank you for reading. Any help would be appreciated.
You're close, but I believe your issue is that you're attempting to set the value to an option that doesn't exist in the list. You need to add the option first:
$('[name="country"]').selectize();
var item = {};
item.name = "Japan"; //Based on your render function, which uses item['name'] and labelField, searchField, etc.
$('[name="country"]')[0].selectize.addOption(item);
$('[name="country"]')[0].selectize.setValue(item.name);

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