Jquery Clone-able Inputs Foreach Overwrites Values
I'm currently creating a clone-able id input field.. the only problem is on submit after validating the id it displays the same values for all duplicates in the console. what I'm
Solution 1:
In function validate_Id
, you're using a global variable idNumber
, which will be assigned by argument values
. So eventually this global variable will be the last validated number.
To solve that, you could change idNumber
to an array indexed by corresponding dep_counter
.
For example, 3 changes should be enough:
replace
var idNumber;
withvar idNumbers = [];
change
validate_Id(values);
to:var idNumber = validate_Id(values);
if (idNumber) { idNumbers.push(idNumber); }
change
dependants['id'] = idNumber;
todependants['id'] = idNumbers[dep_counter];
BTW, you seem to like global variables, which should be avoided when possible. Even worse, you declared some local variables with the same name of the global ones.
Solution 2:
I tried this for you in fiddle.. code:
jQuery('#submit').click(function(){
jQuery('.dependant').each(function(k, v){
dep_counter++
dependants = {};
result['dependant'+dep_counter] = '';
$(v).find(':input').each(function(){
result['dependant'+dep_counter] += $(this).val();
});
//dependants['id'] = idNumber;
});
var jsonData = JSON.stringify(result);
alert(jsonData);
console.log(jsonData);
});
Post a Comment for "Jquery Clone-able Inputs Foreach Overwrites Values"