Create a customized default entry in a input box of a NewForm.aspx based on total count (increment)
-
06-02-2021 - |
Question
New at creating JavaScript Code in SharePoint.
I'm trying to create a customize default value input on my NewForm.aspx.
It's based on counting the number of entries so far (including 0) and then taking that value, add with some text ("RT-1" for example) and have it the default value for the next entry, so it will be incremental. Also, I'll have to create a condition that, if there are no items in a list that it starts at 0 count. Is this possible? Here's what I wrote so far but nothings working:
<script src="/siteassets/jsLib/jquery-3.3.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$SP().list("FormTest").get({fields:"ID"}, function(data) {
var countData=data.length;
$("input[Title='AutoNumb Required Field']").val("RT-"+countData);
});
</script>
Solution
Yes, this is possible provided you run an additional method first that returns the count of entries in that particular list, more specifically a synchronous REST API call. In case the list entries are blank, it can start from 0 as per your requirement. Here is the code below -
<script src="/siteassets/jsLib/jquery-3.3.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var countData = getListEntryCount("FormTest")
$SP().list("FormTest").get({fields:"ID"}, function(data) {
$("input[Title='AutoNumb Required Field']").val("RT-"+countData);
});
function getListEntryCount(listname)
{
var totalEntries = 0;
var myURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle(' "+ listname +" ')/Items?$top=5000";
$.ajax({
url: myURL,
async: false,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
if (data.d.results.length > 0) {
totalEntries = data.d.results.length;
}
},
error: function (error) {
alert("Error: " + JSON.stringify(error));
}
});
return totalEntries;
}
</script>