0

Here is my code..

var  CmalQuery="";
var fieldName="";
$(document).ready(function () {

    $('#btnSearch').on('click', function () {
        txtValue = $('#txtSearch').val();
         fn();
    });
     $('#btnList').on('click', function () {
        fn1();
    });
     $('select').on('change', function () {
       ListName = this.value;
       retrieveFieldsOfListView(ListName);
       txtValue = $('#txtSearch').val();
         // or $(this).val()
    });    
    });



function fn() {
    var context = SP.ClientContext.get_current();
    var user = context.get_web().get_currentUser();
    //Get the Announcements list. Alter this code to match the name of your list  
    var list = context.get_web().get_lists().getByTitle(ListName);
    //Create a new CAML query  
    var caml = new SP.CamlQuery();
    //Create the CAML that will return only items with the titles that contains with 'txtValue' 
   // var CmalQuery = "<View><Query><Where><Or>";
   // CmalQuery += "<Contains><FieldRef Name='EmpName' /><Value Type='Text'>" + txtValue + "</Value></Contains>";
   // CmalQuery += "<Contains><FieldRef Name='Company' /><Value Type='Text'>" + txtValue + "</Value></Contains>";
   // CmalQuery += "</Or></Where></Query></View>"
    caml.set_viewXml(CmalQuery);
    //Specify the query and load the list oject  
   var returnedItems = list.getItems(caml);
    context.load(returnedItems);
    //Run the query asynchronously, passing the functions to call when a response arrives  
    context.executeQueryAsync(onQuerySuccess, onQueryFail);
    function onQuerySuccess(sender, args) {
        //Get an enumerator for the items in the list  
        var enumerator = returnedItems.getEnumerator();
        //Formulate HTML from the list items  
        var markup = 'Items in the Employee Details list that contains with ' + '"' + txtValue + '"' + ': <br><br><table class="table table-striped">';
               //Loop through all the items  
        while (enumerator.moveNext()) {
            var listItem = enumerator.get_current();
            markup += '<tr><td>' + listItem.get_item(fieldName).get_lookupValue() + '</td></tr>';
           // markup += '<td>' + listItem.get_item('JobTitle') + '</td>';
          //  markup += '<td> ' + listItem.get_item('Title') + '</td> ';
          //  markup += '<td>' + listItem.get_item('ManagerName').get_lookupValue() + '</td></tr>';
            //Display the formulated HTML in the displayDiv element  
        }
        markup += '</table>'
        $('#resultsDiv').html(markup);
    }
    function onQueryFail(sender, args) {//Formulate HTML to display details of the error  
        var markup = '<p>The request failed: <br>';
        markup += 'Message: ' + args.get_message() + '<br>';
        //Display the details  
        $('#resultsDiv').html(markup);
    }


}
function fn1() {
    var context = SP.ClientContext.get_current();
    var user = context.get_web().get_currentUser();
    var oWebsite = context.get_web();
    this.collList = oWebsite.get_lists();
    context.load(collList);

    context.executeQueryAsync(onQuerySucceeded,onQueryFailed);
    function onQuerySucceeded() {
        var listInfo = '<table class="table table-striped"><tr>';
        var listEnumerator = collList.getEnumerator();

        while (listEnumerator.moveNext()) {
            var oList = listEnumerator.get_current();

            listInfo += '<tr><td>Title: ' + oList.get_title() + '</td></tr>';

           $("#ddlTitles").append($("<option></option>").html(oList.get_title()));
        }
        listInfo +='</tr></table>'
         $('#resultsDiv').html(listInfo);



    }
    function onQueryFailed(sender, args) {
        alert('Request failed. ' + args.get_message() +
            '\n' + args.get_stackTrace());
    }
}

function retrieveFieldsOfListView(ListName) {

    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getByTitle(ListName);
    var view = list.get_views().getByTitle('All Items');
    var listFields = view.get_viewFields();
    context.load(listFields);
    context.executeQueryAsync(printFieldNames, onError);


    function printFieldNames() {
        var e = listFields.getEnumerator();
      CmalQuery += "<View><Query><Where><Contains><Or>";
        while (e.moveNext()) {
            fieldName = e.get_current();

            CmalQuery += "<FieldRef Name='"+fieldName+"' /><Value Type='Text'>" + txtValue + "</Value>";

            console.log(fieldName);

        }
          CmalQuery += "</Or></Contains></Where></Query></View>";
    }

    function onError(sender, args) {
        console.log(args.get_message());
    }
    }

But while calling fn Function query is failing..

1
  • what is the error you are getting? Check debugger tool (F12)
    – Gaurravs
    Commented Jun 22, 2016 at 5:14

2 Answers 2

2

Here this code will work only in case of 2 fields available in your list. It will not work for more or less than 2 fields.

Reason:

CAML you are formatting is wrong.

While building a CAML query it should be always in pair of 2 conditions

CmalQuery += "<View><Query><Where><Contains><Or>";
        while (e.moveNext()) {
            fieldName = e.get_current();

            CmalQuery += "<FieldRef Name='"+fieldName+"' /><Value Type='Text'>" + txtValue + "</Value>";

            console.log(fieldName);

        }
          CmalQuery += "</Or></Contains></Where></Query></View>";

your this block will not generate a pair of condition. It will generate something like this:

<View><Query><Where><Contains>
<Or>
  <FieldRef Name='fieldName1' /><Value Type='Text'>txtValue1</Value>
  <FieldRef Name='fieldName2' /><Value Type='Text'>txtValue2</Value>
  <FieldRef Name='fieldName3' /><Value Type='Text'>txtValue3</Value>
</Or>
</Contains></Where></Query></View>

Ideally it should be something like this:

<View><Query><Where><Contains>
  <Or>
    <Or>
      <FieldRef Name='fieldName1' /><Value Type='Text'>txtValue1</Value>
      <FieldRef Name='fieldName2' /><Value Type='Text'>txtValue2</Value>
    </Or>
    <FieldRef Name='fieldName3' /><Value Type='Text'>txtValue3</Value>
  </Or>
 </Contains></Where></Query></View>

How To Write Dynamic CAML :

While writing CAML query, you must understand the architecture how it works.

It is pretty simple. You just have to do logical AND/OR operators.

Any operator must have 2 conditions to combine and test.

SCENARIO 1 : This is 1 Operator use with 2 conditions

 <Or>
      <Eq><FieldRef Name='Status' /><Value Type='Text'>(3) TestStatus3</Value></Eq>
       <Eq><FieldRef Name='Status' /><Value Type='Text'>(2) TestStatus2</Value></Eq>              
 </Or>

SCENARIO 2 : This is 2 Operators use with 2 conditions From scenario 1 we got operator now along with that we will add another operator.

<And>
    <Or>
      <Eq><FieldRef Name='Status' /><Value Type='Text'>(3) TestStatus3</Value></Eq>
       <Eq><FieldRef Name='Status' /><Value Type='Text'>(2) TestStatus2</Value></Eq>              
    </Or>
    <Eq><FieldRef Name='Status' /><Value Type='Text'>(1) TestStatus1</Value></Eq>                  
</And>

Here if you notice, <OR> is having two conditions inside it. and that makes 1 condition for outer <And>, so we added another condition block parallel to <OR> operator. Hence 2 conditions are available for <AND>.

Likewise you can build n number of nested conditions.

PS: If you have only 1 condition, it will not require any operator.

3
  • Thanku you soo much
    – user56369
    Commented Jun 22, 2016 at 10:33
  • most welcome :)
    – Gaurravs
    Commented Jun 22, 2016 at 10:34
  • you can accept if worked for you. will be helpful for others
    – Gaurravs
    Commented Jul 8, 2016 at 3:59
1

Remove ' from the query and try like this

CmalQuery += "<FieldRef Name="+fieldName+" /><Value Type=Text>" + txtValue + "</Value>";

Maybe this will work.

3
  • this will not work, ' is must
    – Gaurravs
    Commented Jun 22, 2016 at 5:44
  • I have not tested the above code. But in my case it works.
    – user51831
    Commented Jun 22, 2016 at 5:46
  • values need quotes
    – Gaurravs
    Commented Jun 22, 2016 at 5:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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