Recursion w/ jQuery
by Mike Jacobson
HTML
<div>
<input type="text" name="friends[0user01]">
<input type="text" name="friends[1user01]">
<input type="text" name="friends[2user01]">
<input type="text" name="friends[0user02]">
<input type="text" name="friends[1user02]">
<input type="text" name="friends[2user02]">
<input type="text" name="friends[3user02]">
</div>
JavaScript
function addString(userid) {
var maxInd = this.checkCurrentReturnIndex(userid, 0);
console.log("maxInd ", maxInd);
return 'friends['+maxInd+userid+']';
}
function checkCurrentReturnIndex(userid, currentInd) {
// Recursive function to determine proper, unused index
const len = $('input[name="friends['+currentInd+userid+']"').length;
console.log(currentInd+userid + " len: " + len);
if(!$('input[name="friends['+currentInd+userid+']"').length) {
console.log("returning currentInd ", currentInd);
return currentInd;
} else {
console.log("recur calling with currentId+1 ", (currentInd + 1));
return this.checkCurrentReturnIndex(userid, (currentInd + 1));
}
}
const adding = addString('user01');
console.log("adding: ", adding);