Sartorialist
Sartorialist

Reputation: 301

jQuery Clear Data With Each Form Submission

I have a form where I'd like to allow users to change their inputs. The code below handles the form. I thought that $("tabledata").empty(); would clear it with each submission, but it is not. Instead, the new table is just being appended to the existing.

        jQuery(function () {
            $('#401k').submit(function (e) {
                $("#tabledata").empty();
                var salary = [];
                var data = $('#401k :input').serializeArray();
                currentage = +data[2].value;
                retirementage = +data[3].value;
                contribution = +data[0].value/100;
                salaryincrease = +data[1].value;
                tabledata += "<h3>Starting Salary: " + startingsalaryedit + "</h3><h3>401k Match Percentage: " + match + "%</h3>";
                tabledata += "<table class=bluetable>";
                tabledata += "<tr><th>Age</th><th>Employee Contribution</th><th>Employer Contribution</th><th>Ending Balance (No Contribution)</th><th>Ending Balance (Contributions)</th><th>Ending Balance (Total)</th></tr>";
                for (i = currentage; i <= retirementage; i++) {
                yearsage = i - currentage;  
                salary[i] = startingsalary * Math.pow(1+(salaryincrease/100),yearsage);
                employeecontribution = (salary[i] * contribution).formatMoney(2,'.',',');
                employercontribution = (salary[i] * (match/100)).formatMoney(2,'.',',');
                tabledata += "<tr>";
                tabledata += "<td>" + i + "</td>";
                tabledata += "<td>" + employeecontribution + "</td>";
                tabledata += "<td>" + employercontribution + "</td>";
                tabledata += "</tr>";
                };  
                tabledata += "</table>";    
                $("#tabledata").append(tabledata);  
                e.preventDefault();
            });

Upvotes: 0

Views: 48

Answers (1)

jCobb
jCobb

Reputation: 238

Problem is you are not declaring

var tabledata = ''

Therefore it is global scoped, and you are just appending to the previous. You can console.log tabledata variable to see.

Upvotes: 1

Related Questions