Previously we mentioned how to use the ecmascript object model to operate ordinary list items. But if the list we operate contains a lookup field, what should we do?
First, refer to this article to build our testing environment.
SharePoint Study Notes --- splist -- create a list with the lookup field
1. For the get operation, we use the followingCode
<SCRIPT type = "text/JavaScript">
Function Getlookupvalue (){
VaR Context = New Sp. clientcontext. get_current ();
VaR Web = context. get_web ();
VaR List = web. get_lists (). getbytitle ('testsale ');
VaR Query = sp. camlquery. createallitemsquery ();
Allitems = List. getitems (query );
Context. Load (allitems, 'include (productname, lookupstaffname )');
Context.exe cutequeryasync (function. createdelegate ( This , This . Successgetlookupvalue ),
Function. createdelegate ( This , This . Failedgetlookupvalue ));
}
Function Successgetlookupvalue (){
VaR Textfiled = "";
VaR Listenumerator = This . Allitems. getenumerator ();
While (Listenumerator. movenext ()){
VaR Currentitem = listenumerator. get_current ();
Textfiled + = currentitem. get_item ('productname ') +'-'+ currentitem. get_item ('lookupstaffname'). get_lookupvalue () +' \ n ';
}
Alert (textfiled );
}
FunctionFailedgetlookupvalue (sender, argS ){
Alert ("failed. message:" + args. get_message ());
}
</SCRIPT>
The effect is as follows:
2. For the modification operation, we use the following code:
<SCRIPT type = "text/JavaScript">
Function Setlookupvalue (){
VaR Context = New Sp. clientcontext. get_current ();
VaR Web = context. get_web ();
VaR List = web. get_lists (). getbytitle ('testsale ');
VaR Query = sp. camlquery. createallitemsquery ();
Allitems = List. getitems (query );
Context. Load (allitems, 'include (productname, lookupstaffname )');
Context.exe cutequeryasync (function. createdelegate ( This , This . Successsetlookupvalue), function. createdelegate ( This , This . Failedsetlookupvalue ));
}
Function Successsetlookupvalue (){
VaR Textfiled = ""
VaR Listenumerator = This . Allitems. getenumerator ();
While (Listenumerator. movenext ()){
VaR Currentitem = listenumerator. get_current ();
VaR Newlookupfield = New Sp. fieldlookupvalue ();
Newlookupfield. set_lookupid (2) // Updated with some lookup value for lookupstaffname Column
// Here is an ID of your lookup list item 'Steve ';
Currentitem. set_item ('lookupstaffname', newlookupfield );
Currentitem. Update ();
// Call context.exe cutequeryasync again
}
}
Function Failedsetlookupvalue (sender, argS ){
Alert ("failed. message:" + args. get_message ());
}
</SCRIPT>
The effect is as follows:
It should be noted that in the modification, we use the code
Newlookupfield. set_lookupid (2)
The parameter meaning in this Code is to take the value from the list of data sources bound to lookupitem, for example: