Add choice field option using SPServices

Jan 27, 2014 at 8:19 PM
I am moderately new to SPServices and I have a question:

Is there a way to add a choice to a list field using SPServices?

For example, if I have list "Sample List" with a field "Books" and that field has "Book1", "Book2" and "Book3" as possible options, can I, using SPServices and jQuery, add "Book4" as an option?

I would most likely be adding this code to a Content Editor Web Part or placing it directly on an .aspx page. I need to do this client-side (i.e. without code-behind).
Jan 27, 2014 at 8:27 PM
Yes, this is possible..

You can achieve it with the UpdateList operation of the Lists service. ONe of teh input options to this method is updateFields - that's the one where you would use to re-define the values in the choice Column.

Note that the update can only be done by someone that has full control to the List. Also, For Choice columns, I think you have to actual update with with all the values you want it to have; you can't just say "add one more" to the existing set of values.

/Paul.
Jan 28, 2014 at 1:19 PM
Paul,

Thank you for your quick reply. You don't know of any examples out there of how that would be formatted in the UpdateList operation do you? I understand the basic setup of how a SPServices function would look, but I don't know the syntax of a choice field update. As I said, I am moderately new to SPServices.
Jan 28, 2014 at 1:30 PM
I have done this in the past, but don't recall exactly where... I would suggest searching this forum to see if you find anything...
If I come across the code I used in the past, I'll post.

_________
Paul T

Coordinator
Jan 28, 2014 at 1:34 PM
The documentation page for UpdateList here has an example:
https://spservices.codeplex.com/wikipage?title=UpdateList

M.
Feb 12, 2014 at 7:11 PM
Edited Mar 11, 2014 at 2:33 PM
I did come up with a solution using the references you provided (a hearty thanks to both references), plus this one:

http://devspoint.wordpress.com/2010/10/26/using-spservices-to-get-the-values-of-a-choice-field/

I created a few global variables:

var inputText = "";
var matchText = "";
var arrayList = [];

Created HTML to hold and display my results (simplified for this post):
<table>
   <tr>
      <td style="padding-top: 10px; vertical-align:top">
         <div class="inputBoxButton">
            <input id="inputBox" width="100px" height="15px" ></input>
            <input id="btnSubmit" type="button" value="Add a Choice" height="15px" />
         </div>
      </td>
      <td>&nbsp;</td>
      <td style="padding-top: 10px; vertical-align:top">
         <div id="responseDiv" class="dataview-group-panel">
        <div class="dataview-heading"></div> 
         </div>
      </td>
   </tr> 
</table>
Then, I had to get the current choices from the list. NOTE: I was also checking to see if my new entry already existed in the choice field, hence "iText" (input text) & "mText" (match text is input text with spaces removed):
function loadListInfo(lName, iText, mText) {
      var inputText = iText;
      var matchText = mText;
      $().SPServices({
         operation: "GetList",
         listName: lName,
         async: false,
         completefunc: function(xData, Status) {
            //alert(xData.responseText);
            parseListInfo(xData, Status, inputText, matchText, lName);
         }
      });
} 
A sample call would be:
   inputText = $.trim($("#inputBox").val()); // text box for new option
   matchText = inputText.toLowerCase().replace(/\s/g,''); 
   loadListInfo("My List",inputText,matchText);
With the list's info in hand I then checked the choice field for a match and parsed the current field choices into an array (called in the completefunc from function loadListInfo() above)
function parseListInfo(xData, Status, iText, mText, lname) {
      if(Status == 'success') {
         var inputText = iText;
         var matchText = mText;
         var matchCount = 0;
         $(xData.responseXML).find("Field[DisplayName='<display name of the field you are working with>'] CHOICE").each( function () {
            arrayList.push($(this).text());
            thisText = $(this).text().toLowerCase().replace(/\s/g,'');
            if(thisText == matchText){
               matchCount +=1;
               $(responseDiv).append("<div class='dataview-choice-option'>Match\: Your entry\: <strong>" + inputText + "</strong> / Existing entry\: <strong>" + $(this).text() + "</strong> \(" + lname + ")</div>");
            }
         });
         if(matchCount == 0 && matchText.length == 0){
            $("#responseDiv").empty();
            $("#responseDiv").append("<div class='dataview-choice-option' style='color:red'><strong>You have to enter some text</strong></div>");
         } 
         if(matchCount == 0  && matchText.length > 0 && arrayList.length > 0){
            if (confirm('Add new entry\n' + inputText +'?')) {
                updateChoice(lname, arrayList, inputText); 
            } else {
                 return;
            }
         }
      }
}
Finally, I performed the update -- using the existing choice field entries from the array and added the input text (called from function parseListInfo() above):
function updateChoice(list, array, lName){
      var fieldsToUpdate = '<Fields>';
      fieldsToUpdate += '<Method ID="1"><Field Type="Choice" Name="' + <name of the field you are working with> +'" DisplayName="<display name of the field you are working with>">';
      fieldsToUpdate += '<CHOICES>';
      for(i=0;i<array.length;i++){
         fieldsToUpdate += '<CHOICE>' + array[i] + '</CHOICE>';
      }
      fieldsToUpdate += '<CHOICE>' + inputText + '</CHOICE>';
      fieldsToUpdate += '</CHOICES>';
      fieldsToUpdate += '</Field>';
      fieldsToUpdate += '</Method>';
      fieldsToUpdate += '</Fields>';


      $().SPServices({
         operation: "UpdateList",
         listName: list,
         listProperties:"",
         updateFields: fieldsToUpdate,
         newFields: "",
         deleteFields: "",
         listVersion: "",
         async: false,
         completefunc: function (xData, Status){
            if(Status == 'success'){
               $("#responseDiv").append("<div class='dataview-choice-option'>\"" + inputText + "\" added \(" + list + ")</div>");
            }        
         }
      });
}
There were other steps, like attaching click functions, key up functions and steps specific to my SharePoint site that I left out for brevity, but this should work for any other SharePoint novice, like myself, trying to figure out how to add a choice field option with SPServices & jQuery only.
Feb 13, 2014 at 11:36 AM
Awesome. Thanks for posting back your solution. Very helpful.


--
Paul T.

-- Sent from Mobile