I’m trying to create dynamic tables in my registration page and I’ve given up on using plugins and am just gonna use this append thing. I want the table to show up ONLY if the user selects a certain option. So here’s my html:
<div id="Reg_num2" style="display:none;" >
<button id="AddLine">Add Line</button>
<table border="1px" id="table">
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Phone</td>
<td>Email</td>
<td>Ethnicity</td>
</tr>
<tr>
<td><input type=text /></td>
<td><input type=text /></td>
<td><input type=text /></td>
<td><input type=text /></td>
<td><input type=text /></td>
</tr>
</table>
</div>
And here’s my jquery code:
$(document).ready(function(e) {
$("input[name= 'Reg_num_r']").change( function () {
if($(this).val()==1) {
$("#Reg_num2").hide();
} else {
$("#Reg_num2").show();
}
});
$("#table").on("click", "button", function() {
$(this).closest("tr").remove();
});
$("#AddLine").click(function () {
var row = "<tr><td><input type=text /></td><td><input type=text /></td><td><input type=text /></td><td> <input type=text /></td><td><input type=text /></td><td><button>X</button></td></tr>";
$("#table").append(row);
});
});
There are two problems I am having:
- The table won’t show when the user selects the appropriate radio button. What’s wrong with the code?
- When I click the add button, it submits the entire page instead, how do I fix that?
A
<button>element with notypeattribute specified will betype="submit"by default, so if it’s in a form it will submit the form. Change it to<button type="button">.I’m not sure about your radio button problem, though I’d be inclined to use
.clickrather than.change– please update your question to show the associated html.