CAML Query to get specific item in folder based on dropdown value using Javascript client object model

Hi,
I am using the Javascript Client object model.
I have a custom list and a custom document library.
Custom list contains 2 columns - dlName , dlValue
The document library contains 2 folders - "folder1" ,  "folder2" and contains some images.
The image name starts with the "dlValue" available in the custom list
I am using a visual webpart and using javascript client object model.
I am trying to achieve the below functionality:
1) Load a dropdown with the custom list.
2) set the image based on the value in dropdown.
I have achieved the first option, I have set the dropdown, but not sure how to query the folder and set the image.
Below is the code i have used so far:
//In Visual webpart
<select id="ddlTest" >
</select>
<br/>
<div id="PreviewLayer">
<img id="imgPlaceHolder" runat="server" alt="Image" title="imgPlaceHolder" src=" " />
</div>
// In Javascript file
function RenderHtmlOnSuccess() {
var ddlTest = this.document.getElementById("ddlTest");
ddlTest.options.length = 0;
var enumerator = this.customListItems.getEnumerator();
while (enumerator.moveNext()) {
var currentItem = enumerator.get_current();
var dropdownValue = currentItem.get_item("dlValue");
ddlTest.options[ddlTest.options.length] = new Option(currentItem.get_item("dlName"), dropdownValue);
setImage(dropdownValue); // Not sure how to query the folder and set the image based on value.
// Also if dropdown value is changed, corresponding image should be shown
How to query the folder and based on dropdown value, show the image? Also, how to handle the dropdown value change?
Thanks

Hi,
Here are two links for your reference:
Example of how to Get Files from a Folder using Ecmascript \ Javascript client object model in SharePoint 2010
http://sharepointmantra.wordpress.com/2013/10/19/example-of-how-to-get-files-from-a-folder-using-ecmascript-javascript-client-object-model-in-sharepoint-2010/
SP2010 JSOM Client Object Model: How to get all documents in libraries including all folders recursively
http://sharepoint.stackexchange.com/questions/70185/sp2010-jsom-client-object-model-how-to-get-all-documents-in-libraries-including
In SharePoint 2013, we can also use REST API to achieve it.
http://msdn.microsoft.com/en-us/magazine/dn198245.aspx
Thanks,
Dennis Guo
TechNet Community Support
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
[email protected]
Dennis Guo
TechNet Community Support

Similar Messages

  • Add attachments to List Item using JavaScript Client object model in SP2010

    Hi All ,
    I have created custom form for submitng data in list using javascript client object model/jquery .
    Now I want to add option to uplaod multiple attachments to that list item also .
    Is there option with client object model for uplaoding attachment.
    Thanks
    M
    Manesh G

    Can you try this and let me know
    using (SPSite _site = new SPSite(SPContext.Current.Site.Url))
        using (SPWeb _web = _site.OpenWeb())
         //Let's suppose your Item Id is 1
         int ItemId = 1;
         SPList  oList = _web.Lists["EmployeeList"];
         SPListItem  _item = oList.GetItemById(ItemId);
         if (FileUpload1.HasFile)
               _web.AllowUnsafeUpdates = true;
              Stream fs = FileUpload1.PostedFile.InputStream;
              byte[] _bytes = new byte[fs.Length];
              fs.Position= 0;
              fs.Read(_bytes, 0, (int)fs.Length);
              fs.Close();
              fs.Dispose();
              _item.Attachments.Add(FileUpload1.PostedFile.FileName, _bytes);
              _item.Update();
              _web.AllowUnsafeUpdates = false;

  • Get current item id using JavaScript Client Object Model

    I have a client query that query SharePoint list Items. Lets say it is a document library. I need to get the list item id of each. 
    I can query the Title of the document using this syntax.
    ctx.CurrentItem['Title']
    But when I try 
    ctx.CurrentItem['ID']
    for list item ID, it does not give a value. How can I solve this?

    Hi Malin,
    If you're using the JavaScript Client Object Model, try using the SPListItem.get_item('key') method as in the example below:
    <script>
    ExecuteOrDelayUntilScriptLoaded(function(){
    var arrIds = [];
    var clientContext = new SP.ClientContext();
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query></Query></View>');
    var items = clientContext.get_web().get_lists().getByTitle("Your List Title Here").getItems(camlQuery);
    clientContext.load(items);
    clientContext.executeQueryAsync(Function.createDelegate(this,function(){
    var itemEnumerator = items.getEnumerator();
    while(itemEnumerator.moveNext()){
    var itemId = itemEnumerator.get_current().get_item('ID');
    arrIds.push(itemId);
    alert(arrIds);
    }), Function.createDelegate(this, function(){
    alert("something went wrong");
    },"SP.js");
    </script>

  • CAML query to get Published items in javascript client object

    Hi,
    I am using the Javascript client object model.
    I am trying to use the CAML query to fetch the Published items. (excluding checked-in but not published) .
    I have tried the below code, but I am not able to get the published items alone. I am getting the checked-in but not published items as well.
    function FetchPages() {
    var clientcontext = new SP.ClientContext.get_current();
    var oweb = clientcontext.get_web();
    var olist = oweb.get_lists().getByTitle("Pages");
    var query = new SP.CamlQuery();
    query.ViewXml = "<Where>
    <Eq><FieldRef Name=\"_Level\" /><Value Type=\"Integer\">1</Value></Eq></Where>";
    query.set_viewXml();
    pagesItems = olist.getItems(query);
    clientcontext.load(NewsItems, 'Include(Title,FileLeafRef,FileDirRef)');
    clientcontext.executeQueryAsync(Function.createDelegate(this, this.RenderHtmlOnSuccess), Function.createDelegate(this, this.RenderHtmlOnFailure));
    function RenderHtmlOnSuccess() {
    var enumerator = this.pagesItems.getEnumerator();
    while (enumerator.moveNext()) {
    var currentItem = enumerator.get_current();
    I am getting items which are published as well as items which are checked-in but not published.
    Update: I have tried this query, but the same result:
    <FieldRef Name='_ModerationStatus' /><Value Type='ModStat'>0</Value></Eq>
    How to fix this?
    Also, I checked this:
    http://mysharepointwork.blogspot.com/2011/03/get-published-version-of-list-item.html
    for (int index = 0; index < item.Versions.Count; index++)
    if (item.Versions[index].Level == SPFileLevel.Published)
    // Got the Item
    How to modify the above code for Javascript client object model?
    Thanks

    Hi,
    Please try to modify the query statement as below and do the test again, it works in my environment:
    var query = new SP.CamlQuery();
    query.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'_Level\'/><Value Type=\'Integer\'>1</Value></Eq></Where></Query></View>');
    pagesItems = olist.getItems(query);
    Thanks
    Patrick Liang
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Patrick Liang
    TechNet Community Support

  • How can I get an item and it's attachments from the current list using SP's JavaScript Client Object Model on newform.aspx?

    I only recently learned/read about SharePoint's JavaScript Client Object Model. I'm reading online trying to figure this out but not having much luck.
    On newform.aspx (and dispform.aspx) I want to get the
    current list,
    the last item created, and it's attachments. I now the CAML query I need to get the last item created, but first I have to get the current list and I am not sure how to do that.
    I tried this but it returns null:
    SP.ListOperation.Selection.getSelectedList()

    Hi,
    For your issue, you can get the list name from the new form url and retrieve the list last created item :
    https://social.msdn.microsoft.com/Forums/office/en-US/b90a64f8-2255-41b0-9d91-78335dd4a4cf/get-list-name-from-list-url-through-javascript?forum=sharepointdevelopmentprevious
    http://msdn.microsoft.com/en-us/library/office/hh185007(v=office.14).aspx
    Best Regards,
    Eric
    Eric Tao
    TechNet Community Support

  • Fetching file size using CAML query in Javascript client object model

    Hi,
    I am using the Javascript client object model to retrieve contents of a document library.
    I have a document library, which contains a folder "Folder1" . "Folder1" has a zip file. I would like to get the file size of the zip file.
    I have tried the below code, but not sure, how to fetch the file size.
    function FetchImage() {
    var clientcontext = new SP.ClientContext.get_current();
    var oweb = clientcontext.get_web();
    var olibrary = oweb.get_lists().getByTitle(DocLibrary);
    var query = new SP.CamlQuery();
    query.set_folderServerRelativeUrl("Lists/DocLibrary/folder1/");
    folder = olibrary.getItems(query);
    clientcontext.load(folder, 'Include(Title,ContentType, FileLeafRef,FileDirRef,File)');
    clientcontext.executeQueryAsync(Function.createDelegate(this, this.RenderDataOnSuccess), Function.createDelegate(this, this.RenderDataOnFailure));
    function RenderDataOnSuccess() {
    var ListEnumerator = this.folder.getEnumerator();
    while (ListEnumerator.moveNext()) {
    var currentItem = ListEnumerator.get_current();
    if (_contentType.get_name() != "Folder") {
    var File = currentItem.get_file();
    if (File != null) {
    // Fetch file size
    How to fetch the file size?
    Thanks

    <script>
    function getSize()
            var myFSO = new ActiveXObject("Scripting.FileSystemObject");
            var filepath = document.upload.file.value;
            var thefile = myFSO.getFile(filepath);
            var size = thefile.size;
            alert(size + " bytes");
    </script>
    http://social.msdn.microsoft.com/Forums/en-US/e5d2ff3d-01c7-4cc0-a081-29a4dfbb0fad/getting-the-sharepoint-list-attachment-size-using-javascript?forum=sharepointcustomizationlegacy

  • How to get all previous versions page contents of a publishing page using SharePoint Client Object Model 2010

    How to get all previous versions page contents and other field values of a publishing page using SharePoint Client Object Model 2010?
    Thanks,
    Osmita

    Hi Osmita,
    Greetings.
    Here are the links that helps you. It has code attached to it.
    http://social.technet.microsoft.com/Forums/sharepoint/en-US/a0d2ab40-99ba-4368-8505-1dc559ef6469/get-content-of-previous-version-of-page-sharepoint-2010?forum=sharepointgeneralprevious
    http://social.technet.microsoft.com/Forums/sharepoint/en-US/faaf419f-997e-4150-9911-48cc375c3b46/how-to-get-previous-published-versions-of-publishing-pages-in-sharepoint-2010?forum=sharepointdevelopmentprevious
    Please remember to click 'Mark as Answer' on the answer if it helps you

  • CAML query to get itemcount from sharepoint list based on Month/Year

    Hi,
     I have a SharePoint list with date field. Now I wan't to get item count for each month in Fiscal Year using SP Services. Hence, need a CAML query to get item count . Any suggestions will be appreciated.
    Thanks in Advance.

    When you have your month, you'll need to calculate the first day and last day of the month and convert them to the ISO using to ISOString.
    startDate.toISOString();
    endDate.toISOString();
    function searchList(startDate, endDate) {
        var nURL = "/_vti_bin/lists.asmx";
        var soapEnv = "<?xml version=\"1.0\" encoding=\"utf-8\"?> \
                                 <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
                                  xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"
                                  xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">
                                  <soap:Body> \
                                  <GetListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">
                                  <listName>{YourList}</listName> \
                                  <viewFields></viewFields> \
                                  <query><Query><Where><And><Geq><FieldRef Name='DateField'
    /><Value Type='DateTime'>" + startDate +"</Value></Geq><Leq><FieldRef Name='DateField'><Value Type='Datetime'>"+endDate+"</Leq></And></Where></Query></query> \
                                  <queryOptions><QueryOptions><ViewAttributes Scope='Recursive'/></QueryOptions></queryOptions>
                                  </GetListItems> \
                                      </soap:Body> \
                                  </soap:Envelope>";
        $.ajax({
            url: nURL,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/GetListItems");
            type: "POST",
            dataType: "xml",
            data: soapEnv,
            complete: processResults,
            contentType: "text/xml; charset=utf-8"
    function processResults(xData, status)
      var i;
       result = $(xData.responseText).find("z\\:row, row");
        if (result == undefined) {
            result = $(xData.responseXML).find("z\\:row, row");
        $(result).each(function(i, data) {
        //Magic   
          i++; 
        return i;
    Brandon James SharePoint Developer/Administrator

  • Needs Query to get the cycle time automatically based on the value provided in the UDF on OWOR  table

    Dear all,
    Need a query to get the Cycle time in hr based on the value provide in the udf on OWOR table.
    Details of UDF:-
    1.Start date =10/07/14  (Field Name U_EA_REST)   
    2.Start time =10:00        (Field Name U_EA_REASTARTTIME)
    3.End date =11/07/14    (Field Name U_EA_REET)
    4.End Time=14:00          (Field Name U_EA_REAENDTIME
    Cycle Time=_______      (Field Name U_EA_REACYCLETIME)
    Regards,
    BanugopanRajendran

    Dear all,
    Need a query to get the Cycle time in hr based on the value provide in the udf on OWOR table.
    Details of UDF:-
    1.Start date =10/07/14  (Field Name U_EA_REST)   -  Date Type
    2.Start time =10:00        (Field Name U_EA_REASTARTTIME) - Hour Type
    3.End date =11/07/14    (Field Name U_EA_REET) - Date Type
    4.End Time=14:00          (Field Name U_EA_REAENDTIME - Hour Type
    Cycle Time=_______      (Field Name U_EA_REACYCLETIME) - Hour Type
    Regards,
    BanugopanRajendran

  • Get current loggedin user using silverlight client object model SharePoint 2010?

    Hello,
    How can i get the current loged in user of sharepoint 2010 in silverlight4.XX  version by programtically in C#?
    Thanks
    Lovkesh Patel

    Hi,
    ClientContext clientContext = ClientContext.Current;
    clientContext.Load(clientContext.Web, s => s.CurrentUser);
    clientContext.ExecuteQueryAsync((sender, args) => {
    var currentUser = clientContext.Web.CurrentUser; }, null);
    For more information:
    http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.web.currentuser.aspx and
    http://stackoverflow.com/questions/3441794/retrieve-current-user-login-in-sharepoint-from-a-silverlight-application
    Hope this helps you
    Senior Sharepoint Developer,STS [email protected]

  • Javascript client object model : get value of person or group multi value field (need the username)

    How to get value for a Person or Group field which is of multi value?
    Below is my code:
     var _Assigned = "";
                if (appPendItem.get_item("Assigned").length > 0)
                    if (appPendItem.get_item("Assigned").length ==1)
                        _Assigned = appPendItem.get_item('Assigned').get_lookupValue();
                    if (appPendItem.get_item("Assigned").length >1)
                        for (var i = 0; i < appPendItem.get_item("Assigned").length; i++) 
                            _Assigned = _Assigned + appPendItem.get_item("Assigned")[i].get_lookupValue() + ";";
    I am getting error :  Object doesn't support property or method 'get_lookupValue'
    Please suggest how to do this.
    Thanks

    I tired this code, works perfectly for me:
    var itemId = 3;   
    var targetListItem;
    function runCode() {
        var clientContext = new SP.ClientContext(); 
        var targetList = clientContext.get_web().get_lists().getByTitle('XYZ');
        targetListItem = targetList.getItemById(itemId);
        clientContext.load(targetListItem, 'Users');        
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    function onQuerySucceeded() {
        var users = targetListItem.get_item('Users');
    for(var i = 0; i < users.length; i++) {
      var userValue = users[i];
      console.log(userValue.get_lookupValue());
    function onQueryFailed(sender, args) {
        alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', runCode);
    OutPut:
    Blog | SharePoint Learnings CodePlex Tools |
    Export Version History To Excel |
    Autocomplete Lookup Field

  • Trying to use Web LCID property to get the List name in client object Model

    Hi ,
    I am trying to change the "Personal Documents" list NoCrawl property under MySite using SharePoint Client Object Model. As we use  web.Lists.GetByTitle("Personal
    Documents"); method to get the list,but here problem is :for different language List name is in their language.So I tried to use LCID property of the WEB and
    have taken key-value pair (PersonalSiteOnet_List_PersonalDocuments) from the resource file for that language from 14 hive.
    Example:I have selected Spanish language .there are so many LCID for Spanish language but Microsoft has given only one language pack for Spanish.
    Then,My Question is that
    "All LCID for Spanish language are using same Spanish language pack dictionary file OR something else"
     

    Hi,
    According to your post, my understanding is that your requirement is getting list in different language.
    Here are two ways for your reference:
    1. We can use getById method instead, so that we can avoid the language issue.
    2. We can use an array to store the different list name in different language in you JavaScript code, then use the code snippet below to get the list:
    var userLcid =_spPageContextInfo.currentLanguage;
    var localizedStrings = {
    ListName: {
    _1033: "EnglishName",
    _3082: "SpanishName"
    var listName=localizedStrings.ListName["_" + userLcid];
    var list=web.Lists.getByTitle(listName);
    More information:
    http://msdn.microsoft.com/en-us/library/hh670609.aspx
    http://wellytonian.com/2012/11/language-packs-sharepoint-2010/
    Best Regards
    Dennis Guo
    TechNet Community Support

  • CAML Query to get Items based on Year and Month From Date Column

    Hi All,
           * As we knew that there are default columns in calendar like Stattdate,Title,Location..etc.
            * I required the CAML Query to get the list items of calender of particular Month and Year,So that I can get number of items or evetns are in Calendar
    Can any one help me how can I do this using caml query
    Samar

    Hi Stuart,
                 Thanks for your response,I had chosen 2nd option of our above mention suggestion.But when I try to fetech the data from a calendar it is showing below error .I
    had checked the below code with oter lists by changing Type to text and it worked fine.Can you please help me how can I fetech for the calulated columns
    Error
    "One or more field
    types are not installed properly. Go to the list settings page to delete these
    fields. "
    Code:
     string year="2014";
                string month="February";
                SPSite mysite = SPContext.Current.Site;
                SPWeb myweb = mysite.OpenWeb();
                try
                    SPList mylist = myweb.Lists["Calendar"];
                    SPQuery myquery = new SPQuery();
                    myquery.Query = @"<Where>
                                          <And>
                                           <Eq>
                                             <FieldRef Name='Year'/>
                                             <Value Type='Calculated'>"
    + year + @"</Value>
                                          </Eq>
                                          <Eq>
                                             <FieldRef Name='Month'
    />
                                             <Value Type='Calculated'>"
    + month + @"</Value>
                                          </Eq>
                                         </And>
                                      </Where>";
                    SPListItemCollection totaltiems = mylist.GetItems(myquery);
                   Label1.Text= "Total Number of Items is "+" "+totaltiems.Count.ToString();
                catch (Exception ee)
                    Label1.Text = ee.Message;
                finally
                    myweb.Dispose();
    Calculated Columns
    Samar

  • CAML query to get task assigned to current logged in user

    I want to know the CAML query to get tasks assigned to the currently logged in user
    Nour

    Hi,
    This is the query that worked for me
    <Where>
    <And>
    <Or>
    <Membership Type=’CurrentUserGroups’>
    <FieldRef Name=’AssignedTo’ />
    </Membership>
    <Eq>
    <FieldRef Name=’AssignedTo’  LookupId=’TRUE’ />
    <Value Type=’Lookup’>123</Value>
    </Eq>
    </Or>
    <Neq>
    <FieldRef Name=’Status’ />
    <Value Type=’Text’>Completed</Value>
    </Neq>
    </And>
    </Where>
    Regards,
    Nishant Rana
    http://nishantrana.wordpress.com https://twitter.com/#!/nishantranacrm

  • Conflict between Client object model and Item Updated Event Receiver in sharepoint 2010

    Hello All,
    As per my requirement I have a two custom list.
    Agent Details
    Port Name
    Agent Details contains Agent code, Port Name,  email, address and phone of Agent. Its possible that one Agent Code is connected with multiple Port Name.
    Basically what I am doing is I am getting port name connected with Agent code, using jquery and bind those values with check box(using javascript created dynamically) and bind all with Div tag.
    Now when my custom edit form of Agent list open up it shows me different port name binding with checkbox group.
    when user select the check box and click confirm button my clicent object model script will run and add this selected value into Port Name list. 
    After confirm one more button named Save will enable asking user to edit the email, phone or address value and when I click on save my Item updated event fires which update the values of the selected port name(These port name I am getting from port
    name list) to Agent Details custom list.
    Now when I am trying to update the values my event receiver fires or some times it got stuck(not firing). So could you please help me the possible alternative for this requirements.
    Can we user the Ecma Script(Client object model to preserve the value of selectec port) and Item updated event receiver on the same time?
    Is anything am doing wrong then please guide me.

    Hi,
    As I understand, when you updated values in the agent details list the Item updated event receiver got stuck sometimes.
    The item update event receiver will fire after the item has been saved, and the client object model script or the Ecma Script runs before the item is saved, so there is no conflict between the client object model script and item update event receiver.
    You could find out the reason about the item update event receiver gets stuck by debugging the event receiver.
    When you want to debug your event receivers, you have to attach to OWSTIMER.EXE and wait till they are executed. You can control this behavior using the Synchronization attribute. Also, if you’re looking for an easy way to debug an event receiver without
    having to manually attach a debugger to your code, you can use the System.Diagnostics.Debugger.Launch() method.
    The articles below are about how to debug in the event receiver in SharePoint 2010.
    http://sharepoint-kings.blogspot.jp/2013/02/debugging-event-receivers-in-sharepoint.html
    http://chakkaradeep.com/index.php/event-receivers-in-sharepoint-2010/
    http://sharesaint.com/?p=77
    Best regards,
    Sara Fan
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected]

Maybe you are looking for

  • MP3 encoder VBR Options doesn't work anymore

    Hi everyone ! I always used iTunes mp3 encoder to rip my CD's with the VBR option ON and it worked fine until now. Indeed since 10.3 the VBR option doesn't seem to be working no more : the output is a CBR mp3 file either I tick or not the VBR option

  • Adobe Form Fields to database (either Excel or Access)

    i have a pdf form created from adobe acrobat XI pro that works perfectly.  When submitted, it emails directly to me, which I manually add to a database file stored in Excel.  I'm trying to find a simple way to have the data automatically added to an

  • Edit distribution list

    After updating MobileMe to iCloud, I no longer can edit my distribution lists. This is a problem for contacts who have multiple email addresses. Suggestions?

  • How to handle rules and activities in AII

    Hi experts,                  How to handle rules and activities in AII. Is there any transaction code for it. please give some information, it will be hepful for me

  • Html tags using javax.jws.WebService

    Hi, I am using javax.jws.WebService and I met a problem for html tags. In a String containing "<" and ">", the javax.jws.WebService implmentation of IBM transfered the String with "<" and ">" in the XML reply. How could this translation be avoided? R