none
How to develop the below requirement using JSOM RRS feed

  • Question

  • Hello,

    I have one issue when getting list item and bind to dynamically data table using JSOM. Please provide the code for this requirement.

    I wrote code but i am getting list doesn't exist.

               <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js "></script>
    
                <script type="text/javascript" language="javascript">
                    var _clientContext;
                    var _web;
     		var _SiteURL="site UL";
                     var _ListURL= "Listname";
                    
    		ExecuteOrDelayUntilScriptLoaded(RetrieveListItems, "sp.js");
                    function RetrieveListItems() {
                        _clientContext = new SP.ClientContext(_SiteURL);
                        _web = _clientContext.get_web();
                        var list = _web.get_lists().getByTitle(_ListURL);  
                           
                        var myquery = new SP.CamlQuery.createAllItemsQuery();
                        allItems = list.getItems(myquery);
                        _clientContext.load(allItems);
                        _clientContext.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
                    }
    
                    function success() {
                       // var ID=null;
                        //var Name=null;
                        //var LastName= null;
                        var T=null;
                        var Q=null;
                         var Depart=null;
                       
                        var txtHTML = "";
                        var ListEnumerator = this.allItems.getEnumerator();
                        while (ListEnumerator.moveNext()) {
                            var currentItem = ListEnumerator.get_current();
                            Depart= currentItem.get_item('Column1');
    		       Q = currentItem.get_item('Q');
                            T = currentItem.get_item('T');                       
                            var row = document.createElement("tr");
    
                            txtHTML = txtHTML + "<tr>";
                            txtHTML = txtHTML + "<td>";
                            if (Depart != null) {
                                txtHTML = txtHTML + "<p>"+  +"</p>";
                            }
                            txtHTML = txtHTML + "</td>";
    
                            txtHTML = txtHTML + "<td>";
                            if (T != null) {
                                txtHTML = txtHTML + "<p>" + T+ "</p>";;
                            }
                            txtHTML = txtHTML + "</td>";
    
                            txtHTML = txtHTML + "<td>";
                            if (Q != null) {
                               txtHTML = txtHTML + "<p>" +Q + "</p>";
                            }
                            txtHTML = txtHTML + "</td>";
                            txtHTML = txtHTML + "</tr>";
                        }
                        $("#tblCustomListData").append(txtHTML);
                    }
                    function failed(sender, args) {
                       alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
                    }
                </script>
                <table id="tblCustomListData" border="1">
                    <thead>
     
                        <tr>
                          <th> Depart
                            </th>
                            <th> T
                            </th>
                            <th>Q
                            </th>
                             
                           
                        </tr>
                    </thead>
                </table>
    

    Saturday, March 4, 2017 1:37 PM

All replies

  • The following code sample worked for me:

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js "></script>
    <script type="text/javascript" language="javascript">
    ExecuteOrDelayUntilScriptLoaded(RetrieveListItems,"sp.js");
    function RetrieveListItems() {   
        // here we are fetching current context, but you can also use explicit call (where 'site'  is URL of your site):  var clientContext = new SP.ClientContext(site);
    	var site = "<site_url>";
    	var listName = "<listname>";
        var context = new SP.ClientContext(site);
        var web = context.get_web();
        var list = web.get_lists().getByTitle(listName);
        var query = new SP.CamlQuery.createAllItemsQuery();
        var allItems = list.getItems(query);
        context.load(allItems, 'Include(Title, Id)');
        context.executeQueryAsync(Function.createDelegate(this, function () { onQuerySuccess(allItems); }),
            Function.createDelegate(this, this.onQueryFailed));
    }
    
    function onQuerySuccess(allItems) {
        var ListEnumerator = allItems.getEnumerator();
        while (ListEnumerator.moveNext()) {
            var currentItem = ListEnumerator.get_current();
            // do something with your list item
    	console.log(currentItem);
        }
    }
    function onQueryFailed(sender, args) {
        alert('Error: ' + args.get_message() + '\n' + args.get_stackTrace());
    }
    </script>
    Please test the script and change according to your requirement.


    Avijit Sur

    Saturday, March 4, 2017 3:12 PM
  • Use _ClientContext.loadQuery(ListName, Include Items properites) as Avijit suggested. When you write CAML query, Load properties returns unknown error.

    Thanks & Regards

    Lalith

    ----------------------------------------------------

    Please mark as answer, if solution helps you

    Saturday, March 4, 2017 3:54 PM
  • Thnaks you support.

    How to create Table dynamically and bind list data to this table and change the background color based on T choice column .

    Saturday, March 4, 2017 5:26 PM
  • Please use below code which I created for one of my projects. I can not build exact the way you want. But this code will helps you for your requirement.

    TableCSFDynamicTable = newTable();

                    CSFDynamicTable.CssClass = "rowStyle";

                   

    foreach(Microsoft.SharePoint.Client.ListItemCSFitem initems)

                    {                       

    TableRowrow = newTableRow();        

    TableCellcell = newTableCell();                   

    LabellblCSFtext = newLabel();

                        lblCSFtext.Text = CSFitem.FieldValues["Title"].ToString();

                        cell.Controls.Add(lblCSFtext);

                        cell.CssClass =

    "HeaderStyle";

                        row.Cells.Add(cell);                   

    for(inti = 1; i <= 7; i++)

                        {                       

    TableCellratingCell = newTableCell();                       

    LabellblRating = newLabel();                       

    switch(i)

                            {                           

    case1:

                                    lblRating.Text = i.ToString() +

    "-"+ "Strongly Disagree";                               

    break;                           

    case4:

                            lblRating.Text = i.ToString() +

    "-"+ "Netural";

                                 

    break;     

    case7:

                                    lblRating.Text = i.ToString() +

    "-"+ "Strongly agree";                               

    break;

    default:

                                    lblRating.Text = i.ToString();

                                   

    break;

                            }

                            ratingCell.Controls.Add(lblRating);

                            ratingCell.CssClass =

    "HeaderStyle textAlign";

                            row.Cells.Add(ratingCell);

                            row.CssClass =

    "HeaderStyle";

                            CSFDynamicTable.Rows.Add(row);

                        }

     
    Thanks

    Lalith

    ---------------------------------

    please mark as answer,  if solution helps you.


    • Edited by kirank.gutthi Saturday, March 4, 2017 7:37 PM Alighed
    Saturday, March 4, 2017 5:37 PM
  • Adding additional code along with my earlier code.

    TableRow trBtn = newTableRow();               

    TableCelltcBtn = newTableCell();               

    //tcBtn.CssClass = "rowStyle";

                    tcBtn.Controls.Add(btnSubmit);

                    trBtn.Cells.Add(tcBtn);              

    // CSFDynamicTable.Rows.Add(trBtn);               

    TableRowtrSuccessMesg = newTableRow();               

    TableCelltcSuccessMesg = newTableCell();

     lblSuccessMesg = newLabel();

    lblSuccessMesg.Text =

    "Your feedback request has been submitted successfully. Thank you.";

     lblSuccessMesg.CssClass =

    "SuccessMesg";

    lblSuccessMesg.Visible =

    false;

                    tcSuccessMesg.Controls.Add(lblSuccessMesg);

                    trSuccessMesg.Cells.Add(tcSuccessMesg);

                    CSFDynamicTable.Rows.Add(trSuccessMesg);

                    CSFDynamicTable.Rows.Add(trBtn);

                    form1.Controls.Add(CSFDynamicTable);


    • Edited by kirank.gutthi Saturday, March 4, 2017 7:40 PM Aligned
    Saturday, March 4, 2017 5:38 PM
  • Hi,

    Based on your sample code, I think you have build the table based on list data dynamically, so you could add css for your TD element based on T, then control the background based on css.

    Fake code:

     

    if (T != null) {
    	if(T==''){
    		 txtHTML = txtHTML + "<td class='class1'>";
    	}
    	else
    		txtHTML = txtHTML + "<td class='class2'>";
    	txtHTML = txtHTML + "<p>" + T+ "</p>";;
     }

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Monday, March 6, 2017 8:17 AM
  • Thanks To all for supporting to me.


    Tuesday, March 7, 2017 1:06 PM
  • Please mark as answer, if you find solution.

    Tuesday, March 7, 2017 1:09 PM
  • Hi,

    I am checking to see how things are going there on this issue. Please let us know if you would like further assistance.

    You can mark the helpful post as answer to help other community members find the helpful information quickly.

    You can also share your own solution here and mark it as answer, and we can learn from each other.

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Thursday, March 9, 2017 7:39 AM
  • Hello,

    I written the below code it is working fine from my end. If any another ways is there please replay with solution

    <script type="text/javascript"  src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
    <script type="text/javascript"  src="/_layouts/15/sp.runtime.js"> </script>
    <script type="text/javascript"  src="/_layouts/15/sp.js"> </script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
    <script type="text/javascript"  src="/sites/DevSite/SiteAssets/Common.js"> </script>
    <script type="text/javascript"  src="/sites/DevSite/SiteAssets/SPAPI_Core.js"> </script>
    <script type="text/javascript"  src="/sites/DevSite/SiteAssets/SPAPI_Lists.js"> </script>
    <script type="text/javascript"  src="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
    
    
    
    <div>
       
    <style type="text/css">
           
           #tblAllItems {
          border-spacing: 10;
           width: 100%;
           }
      th, td {
        border: 1px solid #ccc;
        padding: 10px;
        text-align: left;
         }
         
          td:nth-child(2) { background-color: yellow; } 
          td:nth-child(3) { background-color: yellow; } 
          td:nth-child(5) { background-color: yellow; }
          td:nth-child(4) { background-color: yellow; }
          td:nth-child(6) { background-color: yellow; }
          td:nth-child(1) { background-color: yellow; }
          
      
    
    
         </style>
    
    
    
    <script type="text/javascript">
      var yearArray=[];
      var monthArray=[];
        $(document).ready(function () {               
            getAllListItems(); 
               
        });
      
      
        function getAllListItems() {         
          //debugger;
             item2Show = 110;
          
            var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('DashBoardList')/items?select=id,Sub_Department,Ontime__x0020_delivery,Quality,Meetingdate,Month&$Top=" + item2Show + " ";
            var requestHeaders = { "accept": "application/json;odata=verbose" };
    
            $.ajax({
                url: requestUri,
                contentType: "application/json;odata=verbose",
                headers: requestHeaders,
                success: onSuccess,
                error: onError
            });
        }
    
        function onSuccess(data, request) {
            riskTable = "";
            var myLog = data.d;
    
            for (var resultType in myLog.results) { 
    		yearArray.push(myLog.results[resultType].Year);
    		monthArray.push(myLog.results[resultType].Month);
                
                riskTable = "<tr><td><span>" + myLog.results[resultType].Sub_Department  + "<span></td>";
                
                riskTable = riskTable + "<td><span>" + myLog.results[resultType].Meetingdate .split('T')[0] + "<span></td>";
                var status =  myLog.results[resultType].Ontime__x0020_delivery;
               
      				 switch(status)
      				 {
      				 case 'Not ok':
               
                   riskTable = riskTable + "<td  style='background-color:Red;'><span>" +  myLog.results[resultType].Ontime__x0020_delivery + "<span></td>";
                   break;
    
                  
                  case 'Ok':
                  riskTable = riskTable + "<td  style='background-color:Green;'><span>" +  myLog.results[resultType].Ontime__x0020_delivery + "<span></td>";
                  break;
    
                  
                  case 'Improve' :
                  
                 riskTable = riskTable + "<td style='background-color:goldenrod;'><span>" +  myLog.results[resultType].Ontime__x0020_delivery + "<span></td>";
                  break;
    
      				 }
      				 
      				 
      				 
               
                var Quality_Value =  myLog.results[resultType].Quality;
                switch(Quality_Value)
                {
                case 'Not ok':
               
                   riskTable = riskTable + "<td style='background-color:Red;'><span>" +  myLog.results[resultType].Quality + "<span></td>";
                   break;
    
                  
                  case 'Ok':
                  riskTable = riskTable + "<td style='background-color:Green;'><span>" +  myLog.results[resultType].Quality + "<span></td>";
                  break;
    
                  
                  case 'Improve' :
                  
                  riskTable = riskTable + "<td style='background-color:goldenrod;'><span>" +  myLog.results[resultType].Quality + "<span></td>";
                  break;
    
                }
               
        
                $('#tblAllItems').append(riskTable);
    			
    			
            }
            
    		var uniqueYear = yearArray.filter(function(itm,i,a){
    			return i == yearArray.indexOf(itm);
    			});
    		
    		var uniqueMonth = monthArray.filter(function(itm,i,a){
    			return i == monthArray.indexOf(itm);
    			});
    		//alert(uniqueMonth);
    		
    		for(var i=0;i<uniqueYear.length;i++)
    		{
    		$("#years").append("<option>"+uniqueYear[i]+"</option>");
    		}
    		for(var j=0;j<uniqueMonth.length;j++)
    		{
    		$("#month").append("<option>"+uniqueMonth[j]+"</option>");
    		}
    
        }
    
        function onError(error) {
            alert("error");
        }
        
        
       
    function getFilterValues() {         
          debugger;
           var selectmonth=$("#month").val();
           var selectyear=$("#years").val();
           
          
    	  riskTable='';
    	  $('#tblAllItems').empty();
    	  riskTable ="<tr ><th align='Left'>Sub_Department </th><th align='Left'>Meetingdate </th> <th align='Left'>Quality </th><th align='Left'>Ontime_delivery</th></tr>";
    	  var listName="DashBoardList";
    		 $('#tblAllItems').append(riskTable);
    
    var query="<Query><Where><And><Eq><FieldRef Name='Year'/><Value Type='Calculated'>"+$("#years").val()+"</Value></Eq><Eq><FieldRef Name='Month'/><Value Type='Calculated'>"+$("#month").val()+"</Value></Eq></And></Where></Query>";
    	
    
     listItems = getCommonListData('',1000,listName,query, '','','','','')  
     
    //var listItems = getCommonListData('',1000,listName,query, '','','','','');
    		
    if(listItems != null && listItems.length > 0)
    		
    {
    	    	
    $(listItems).each(function () 
    	    	
    {
    	    	  
    //alert(this.getAttribute('ows_Title'));
    //riskTable =  "<tr><td><li><span><a class='tt-Anchor'  target=_blank href=" + _spPageContextInfo.webAbsoluteUrl + "/_layouts/15/listform.aspx?PageType=4&ListID=B1074C07B-EB5A-44E2-B63C-48955BC00C0C&ID=" + this.getAttribute('ows_ID') + "&source=" + _spPageContextInfo.webAbsoluteUrl + ">" +this.getAttribute('ows_ID') + "</a></span></li></td>";
    
                 riskTable = "<tr><td><span>" + this.getAttribute('ows_Sub_Department')  + "<span></td>";
    			riskTable = riskTable + "<td><span>" + this.getAttribute('ows_Meetingdate').split(' ')[0] + "<span></td>";
                  var status1 = this.getAttribute('ows_Quality');
    			  if(status1=='Not ok')
    			  {
    			  riskTable = riskTable + "<td style='background-color:Red; class='Yescell'><span>" + this.getAttribute('ows_Quality') + "<span></td>";
    			  }
    			 else if(status1=='Ok')
    			 {
    			 riskTable = riskTable + "<td style='background-color:Green; class='Nocell'><span>" +  this.getAttribute('ows_Quality') + "<span></td>";
    			 }
    			 else if(status1=='Improve')
    			{
    			riskTable = riskTable + "<td style='background-color:goldenrod; class='Nocell'><span>" + this.getAttribute('ows_Quality') + "<span></td>";
    			}
    
    			//
    
    			var status2 = this.getAttribute('ows_Ontime__x0020_delivery');
    			if(status2=='Not ok')
    			{
    			riskTable = riskTable + "<td style='background-color:Red;  class='Yescell'><span>" +  this.getAttribute('ows_Ontime__x0020_delivery') + "<span></td>";
    			}
    			else if(status2=='Ok')
    			{
    			riskTable = riskTable + "<td style='background-color:Green; class='Nocell'><span>" + this.getAttribute('ows_Ontime__x0020_delivery') + "<span></td>";
    			}
    			else if(status2=='Improve')
    			{
    			riskTable = riskTable + "<td style='background-color:goldenrod; class='Nocell'><span>" + this.getAttribute('ows_Ontime__x0020_delivery') + "<span></td>";
    			}
                
                $('#tblAllItems').append(riskTable);
                
                
    	    	
    });
    }
    	    
    
    
    }
    
        
        
    </script>
    <div>
    Year:<select id= "years"> <option value="">Select</option></select>
    Month:<select id= "month"> <option value="">Select</option></select>
    <input type="button" onclick="getFilterValues()" value="Filter">
    </div>
    <table id='tblAllItems'>
           
           <tr >
               
               <th align="Left">Sub_Department </th>    
               <th align="Left">Meetingdate </th>
               <th align="Left">Ontime_delivery</th> 
               <th align="Left">Quality</th>          
           </tr>
           
    </table>     
    </div>
    

    Thursday, March 23, 2017 5:48 AM
  • Hi,

    Thanks for your sharing, you could mark your solution as answer, so it may help other community members find the helpful information quickly

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Wednesday, March 29, 2017 8:38 AM