Reputation: 6389
In the function below, I'm finding the max count of an ID then adding 1. Everything works, except the new values being added to the DOM aren't seen, therefore they are not incremented upon calling the function a second time.
Am I not adding the new values to the DOM correctly?
function addEdu(){
var currentCount = $('input.uniqueId').val();
currentCount = Math.max(currentCount);
var nextCount = parseInt(currentCount) + 1;
var newEdu = "<input type='hidden' name='fieldId[]' value='" + nextCount + "' class='uniqueId' /><p class='dual'><input type='text' name='educationTitle[]' "; //Shortened for clarity
$("#eduHistory").append(newEdu);
$( ".datepicker" ).datepicker();
}
Upvotes: 0
Views: 48
Reputation: 21881
The way you're trying to determine the next .uniqueId
is wrong.
First of all, $("input.uniqueId").val()
will give you the value of the first element in the selection.
The second problem is with Math.max(currentCount)
which will always return the value of currentCount
which is, as already mentioned, the value of the first element.
This should work as intended:
// get an array with all uniqueIds
var currentIds = $("input.uniqueId").map(function() {
return parseInt($(this).val(), 10);
});
// determine the biggest uniqueId
var currentCount = Math.max.apply(Math, currentIds);
// next uniqueId (if there is no "input.uniqueId" then currentCount will be -Infinity)
var nextCount = (currentCount === -Infinity ? 0 : currentCount) + 1;
// ...
Upvotes: 1
Reputation: 97672
$('input.uniqueId').val()
will give you the value of the first input with class uniqueId
. If you are only expecting there to be one such input just change the value of the input. Otherwise you'll probably have to select the last input $('input.uniqueId:last').val()
.
Also Math.max takes 2 parameters, what is its purpose?
Upvotes: 2