0

I am trying to insert dynamic data (question number, question and answer checked) to a new sharepoint list. The data needs to be read from another list, i.e. "Questions1List". I have a quiz page in HTML (.aspx). The data to be captured in another list (StudentList) is:

  1. The student ID that student fills in a textbox
  2. Question number coming from Questions1List
  3. Question number coming from Questions1List
  4. Answer (radio button value) checked by student. I am not getting how to insert those values (values from Questions1List) to StudentList dynamically.

I want to capture StudentID, Question number, Question and Answer. Whenever I am trying to insert the values in StudentList, the last value of question number is coming while question and answer both are coming as "NaN". Please help me to resolve this issue.

HTML Code:

<html>

<head>
<meta name="WebPartPageExpansion" content="full" />
<link rel="stylesheet" type="text/css" href="bootstrap.css"/>   
<script  type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" 
src="https://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
<script src="/_layouts/15/init.js" type="text/javascript"></script>
<script src="/_layouts/15/sp.core.js" type="text/javascript"></script>
<script src="/_layouts/15/sp.runtime.js" type="text/javascript"></script>
<script src="/_layouts/15/sp.js" type="text/javascript"></script>

<script  type="text/javascript" src="jsom.js"></script>
<script src="https://rawgit.com/kswedberg/jquery-smooth- 
scroll/master/jquery.smooth-scroll.js"></script>

</head>

<body>

<header>
        <div class="logo">
            <a href=""><img alt="" src="Logo.jpg" typeof="foaf:Image" 
class="site-logoDiv"></a>

            </div>       
<nav class="navbar navbar-inverse">
<div class="container-fluid">

<ul class="nav navbar-nav">
            <li class="active"><a href="#">Home</a></li>

                  <li><a href="">Register</a></li>
                  <li><a href="">Login</a></li>
                  <li><a href="">About Us</a></li>
                  <li><a href="">Terms of Use</a></li>
                  <li><a href="">Privacy Statement</a></li>
                  <li><a href="">Help</a></li>
</ul>
</div>

</nav>

        </header>

        <form>

        <section>
            <div class="studID">
            <label id="IDlabel">Student ID:</label>
            <input type="text" id="stID" name="studentID" placeholder="Please enter your ID" />
            </div>
        </section>
        <div class="container">

            <div class="testContent">

            <h2 id="titleText">MULTIPLE CHOICE QUESTIONS</h2>

            </div>

            <div id="qDiv" class="questionDiv"></div>

            <div id="optDiv" class="optionsDiv">
            </div>

            <div class="submitBtnDiv">

                <input type="submit" class="submitBtn" value="SUBMIT" onclick="addListItem()"/>

            </div>          
        </div>  

        </form>     
        <footer style="margin-top:100px;">

        <div class="container fttop">

            <div class="col col-lg-3 col-md-3 col-sm-5">
              <h2>Contact Us</h2>
              <hr>
              <p>Institute Name, <br>
            #123, M. G. road,<br>
            Near IIT College,<br>
            City - 122 433<br>
            <img src="mobile_icon.png"> 123456789<br>
            <img src="email_icon.png"> contact@institute_name.com
              </p>
            </div>

            <div class="col col-lg-3 col-md-3 col-sm-5">
                  <h2>Important Links</h2>
                   <hr>
            <ul>
            <li class="active"><a href="#">Home</a></li>
                    <li><a href="">Register</a></li>
                  <li><a href="">Login</a></li>
                  <li><a href="">About Us</a></li>
                  <li><a href="">Terms of Use</a></li>
                  <li><a href="">Privacy Statement</a></li>
                  <li><a href="">Help</a></li>
            </ul>   
            </div>

        </div>

        <div class="ftbottom">
          <div class="container">
            © institute_name 2019 - All Rights Reserved.
          </div>
        </div>      
      </footer>
</body>

</html>

JS code:

function retriveListItem()  
{      

    var siteUrl = '/sites/NewWorkSite';
    var context = new SP.ClientContext(siteUrl);  
    var list = context.get_web().get_lists().getByTitle('Questions1List');  
    var caml = new SP.CamlQuery();  
    caml.set_viewXml("<View><Query><OrderBy><FieldRef Name='QuestionNumber' Ascending='TRUE' /></OrderBy></Query></View>");  
    returnedItems = list.getItems(caml);  
    context.load(returnedItems);  
    context.executeQueryAsync(onSucceededCallback, onFailedCallback);  
}  

$(document).ready(function () 
{ ExecuteOrDelayUntilScriptLoaded(retriveListItem, "sp.js"); 
});


function onSucceededCallback(sender, args)  
{  
    var enumerator = returnedItems.getEnumerator();  
    //Formulate HTML from the list items   
    var MainResult = 'Items in the Divisions list: <br><br>';  
    //Loop through all the items   
    while(enumerator.moveNext())  
    {  
        var count = count + 1;         
        var listItem = enumerator.get_current();  
        var qNo = listItem.get_item("QuestionNumber");   
        var qst = listItem.get_item("Question");   
        var optionA = listItem.get_item("OptionA");         
        var optionB = listItem.get_item("OptionB");
        var optionC = listItem.get_item("OptionC");
        var optionD = listItem.get_item("OptionD");   

                $('#qDiv').append("<label>" + qNo+ "." + "</label>&nbsp" + "<label id='qts'>" + qst + "</label>" + "</br>" 
                + "<label>A: </label>&nbsp" + "<input id='one' class='rdBtn' type='radio' name = '" + qNo+ "' value = 'A'/>&nbsp" + optionA  + "&nbsp</br>"
                + "<label>B: </label>&nbsp" + "<input id='two' class='rdBtn' type='radio' name = '" + qNo+ "' value = 'B'/>&nbsp" + optionB + "</br>"
                + "<label>C: </label>&nbsp" + "<input id='three' class='rdBtn' type='radio' name = '" + qNo+ "' value = 'C'/>&nbsp" + optionC + "</br>"
                + "<label>D: </label>&nbsp" + "<input id='four' class='rdBtn' type='radio' name = '" + qNo+ "' value = 'D'/>&nbsp" + optionD + "</br>" + "</br>");

    }                             
}  
        //This function fires when the query fails   
function onFailedCallback(sender, args)  
{  
        //Formulate HTML to display details of the error   
        var markup = '<p>The request failed: <br>';  
        markup1 = 'Message: ' + args.get_message() + '<br>';  
        //Display the details   
} 


// Adding list items code starts here

function addListItem()  
{
var itemArray = [];
var clientContext = SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('StudentList');
for (var i = 0; i < 5; i++) {
var itemCreateInfo = new SP.ListItemCreationInformation();
var oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('StudentID', "100" );  
oListItem.set_item('QuestionNumber', "1"); // Here I need dynamic value from Questions1List
oListItem.set_item('Question', "Some Question"); // Here I need dynamic value from Questions1List
oListItem.set_item('Answer', "Some Answer"); // Here student answer option checked value needed
 oListItem.update();
itemArray[i] = oListItem;
clientContext.load(itemArray[i]);
}

clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);

}

function onQuerySucceeded() {
itemArray.forEach(function(item) {
    console.log(item.get_id());
});
}

function onQueryFailed(sender, args) {

alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}  

Questions1ListImage

HTML Page

StudentList

0

If I understand correctly, you are populating a form with values from the Questions list, and then you want to record the responses in another list, including Student ID.

First I would ask if there is a specific reason you are creating the form from scratch instead of using a more "out of the box" solution.

For example, you could use the built-in "Survey" list type. It allows you to create a series of questions and possible answers, all within a single list. As well, it has native security features to prevent respondents from seeing other users' answers.

Survey List enter image description here

Alternately, if you have O365 you could use Microsoft Forms. It is very much like the "Survey" list but is mobile-friendly and works independently of SharePoint.

If neither of those options is suitable then: I am not sure I entirely understand the issue you're having. It sounds like you are able to get some data from the form into the new list item in StudentList, but that some of the data is also coming back as NaN. Can you explain in more detail what you mean by that?

Also, from the code you posted it looks like the addListItem function is not actually getting anything from the form. As well, the form is not configured to allow you to easily get each question's value using jQuery. So I would recommend these changes:

In onSucceededCallback, enclose each question in a DIV with a unique, index-based ID so that you can enumerate through them again in addListItem. For this to work you need to define count outside the enumeration loop; otherwise it gets overwritten on each pass.

function onSucceededCallback(sender, args) {
    var enumerator = returnedItems.getEnumerator();
    //Formulate HTML from the list items   
    var MainResult = 'Items in the Divisions list: <br><br>';
    //Loop through all the items   
    var count = 0;
    while (enumerator.moveNext()) {
        var listItem = enumerator.get_current();
        var qNo = listItem.get_item("QuestionNumber");
        var qst = listItem.get_item("Question");
        var optionA = listItem.get_item("OptionA");
        var optionB = listItem.get_item("OptionB");
        var optionC = listItem.get_item("OptionC");
        var optionD = listItem.get_item("OptionD");

        // Create a container div to hold the question and possible answers
        var qContainer = jQuery('<div/>').attr('id', 'question-' + count); // now each question has a unique ID

        // Append answers to container div
        qContainer.append("<label id='qNo'>" + qNo + "." + "</label>&nbsp" + "<label id='qts'>" + qst + "</label>" + "</br>"
            + "<label>A: </label>&nbsp" + "<input id='one' class='rdBtn' type='radio' name = '" + qNo + "' value = 'A'/>&nbsp" + optionA + "&nbsp</br>"
            + "<label>B: </label>&nbsp" + "<input id='two' class='rdBtn' type='radio' name = '" + qNo + "' value = 'B'/>&nbsp" + optionB + "</br>"
            + "<label>C: </label>&nbsp" + "<input id='three' class='rdBtn' type='radio' name = '" + qNo + "' value = 'C'/>&nbsp" + optionC + "</br>"
            + "<label>D: </label>&nbsp" + "<input id='four' class='rdBtn' type='radio' name = '" + qNo + "' value = 'D'/>&nbsp" + optionD + "</br>" + "</br>");

        // append the container to the Questions DIV in the form
        jQuery('#qDiv').append(qContainer);
        count = count + 1;
    }
}

In addListitem use the index variable of the for loop to retrieve each needed value from the form, identified by the ID of the question container in which it is located:

function addListItem() {
    var itemArray = [];
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('StudentList');
    for (var i = 0; i < 5; i++) {
        var itemCreateInfo = new SP.ListItemCreationInformation();
        var oListItem = oList.addItem(itemCreateInfo);
        oListItem.set_item('StudentID', jQuery('#stdID').val());
        oListItem.set_item('QuestionNumber', jQuery("#qNo", '#question-' + i).text()); // Get the question number
        oListItem.set_item('Question', jQuery("label#qts", '#question-' + i).text()); // Get the question text from the form
        oListItem.set_item('Answer', jQuery("input[class='rdBtn']:checked", '#question-' + i).val()); // Get the value of the checked radio button in the question container
        oListItem.update();
        itemArray[i] = oListItem;
        clientContext.load(itemArray[i]);
    }

    clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);

}

This should work in theory but I have not tested it thoroughly; YMMV. Anyway, does this help?

  • One small bug fix - when creating the divs you increment the count variable before you make the first one (so count is already 1 for the first one), but then when reading them in the for loop you start looking when i is 0... – Dylan Cristy Apr 8 at 15:21
  • @DylanCristy thanks for pointing this out. I've fixed it in the post. – Chris Odegard Apr 8 at 17:38
  • Thanks Chris Odegard and Dylan Cristy for your suggestions. I try that and check what happens. – Purushottam Patil Apr 9 at 3:36
  • @ Chris Odegard Actually, I was not aware of the other options for creating forms. The student ID also needs to be captured that's why I chose custom form. – Purushottam Patil Apr 9 at 3:51
  • Hi @Chris Odegard! It is working fine. Thanks a lot for the help. All the list items are getting inserted as expected. – Purushottam Patil Apr 9 at 5:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.