简体   繁体   中英

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();
            });

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM