How to read the Lookup column value using JS/Jquery?
-
15-01-2021 - |
Question
One of the Projects I am working on, I have a requirement to read the lookup column Value in a document library while uploading a document.
For example, if someone uploads a document to the SharePoint library, they will select a value in the lookup field(mandatory) and once they hit on Save/CheckIn to save document in the library, it should alert with the lookup value that user chose.
Please let me know, how to achieve this using JSOM approach?
Solution
We can add the custom jQuery code in the default edit form like the picture below. And edit the default edit form, add the script web part and add the custom jQuery code in the script web part.
There is a demo.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#ctl00_ctl40_g_208827b4_894c_4842_bbdf_f311bae2ed4a_ctl00_ctl02_ctl00_toolBarTbl_RightRptControls_ctl00_ctl00_diidIOSaveItem").click(function () {
var value = $("select[title='look1 Required Field']").find("option:selected").text();
alert(value);
});
});
</script>
The result as below, when I click the “check in”, it will alert the selected value in lookup column.
There is a similar post:
To change the name of the file as the “Name and lookup column value”, you could refer to the demo below.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var look1 = $("select[title='look1 Required Field']").find("option:selected").val();
var name = $("input[title='Name Required Field']").val();
$("input[title='Name Required Field']").val(name+" "+look1);
$("select[title='look1 Required Field']").change(function(){
$("input[title='Name Required Field']").val(name+" "+$(this).find("option:selected").val());
});
});
</script>