Question

I have the below code which grabs all items from a List with the following structure:

enter image description here

I want to limit the query results by a specific value of 'ID' (so when the code gets to the enumerator part, I don't have to change that code, as the enumerator will only run once - the specific value of ID to be used will be generated by code elsewhere but for now just need it to work with a manual value).

I've tried a fair few different ways from blog posts and questions here but I can't seem to get it to work - either I still get all items in the List, or none at all.

Any suggestions? Code I'm using is below:

<div id="companiesSpace">Change me</div>

<script type="text/javascript">
var clientContext;
var oWeb;
var companiesList;
var allCompanies;
var companiesMarkupBlock = "<b>Companies</b><br />"

function getCurrentList(listName) {
      thisList = oWeb.get_lists().getByTitle(listName);
      return thisList;
  }

function runOnFail() {
    alert("Failed to get client context");
  }

function runOnSuccess() {
    var camlQuery = new SP.CamlQuery();
    var camlQueryString = "<Query><OrderBy><FieldRef Name='ID' /></OrderBy></Query>";
    camlQuery.set_viewXml(camlQueryString);
    allCompanies = companiesList.getItems(camlQuery);
    clientContext.load(allCompanies);
    clientContext.executeQueryAsync(runOnSecondSuccess,runOnSecondFail);
  }

function runOnSecondFail() {
    alert("Failed to issue CAML query");
  }

function runOnSecondSuccess() {
  var companyEnum = allCompanies.getEnumerator();
  while (companyEnum.moveNext()) {
      var currentCompany = companyEnum.get_current();
      var thisCompanyId = currentCompany.get_item('ID');
      var thisCompanyName = currentCompany.get_item('companyName');
      companiesMarkupBlock += thisCompanyId;
      companiesMarkupBlock += " : ";
      companiesMarkupBlock += thisCompanyName;
      companiesMarkupBlock += "<br />";
    }
  document.getElementById('companiesSpace').innerHTML = companiesMarkupBlock;
  }

function getContacts() {
    clientContext = SP.ClientContext.get_current(); 
    oWeb =  clientContext.get_web();
    companiesList = getCurrentList('Companies');
    clientContext.load(companiesList);
    clientContext.executeQueryAsync(runOnSuccess,runOnFail);
  }

SP.SOD.executeFunc('sp.js','SP.ClientContext',getContacts);
</script>
Was it helpful?

Solution

Modify

var camlQueryString = "<Query><OrderBy><FieldRef Name='ID' /></OrderBy></Query>";

to

var camlQueryString = "<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Number'>{ADD LIST ITEM ID HERE}</Value></Eq></Where></Query></View>";
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top