Restricted form with multiple forms
http://stackoverflow.com/a/13637976/189937
by jesus_tesh
HTML
<h2>Table A</h2>
<table id="tableA" border="1">
<tr>
<td>
A1
</td>
<td>
<input type="radio" name="a1" value="1" /> Yes
<input type="radio" name="a1" value="0" /> No
</td>
</tr>
<tr>
<td>
A2
</td>
<td>
<input type="radio" name="a2" value="1" /> Yes
<input type="radio" name="a2" value="0" /> No
</td>
</tr>
<tr>
<td>
A3
</td>
<td>
<input type="radio" name="a3" value="1" /> Yes
<input type="radio" name="a3" value="0" /> No
</td>
</tr>
</table>
<h2>Table B</h2>
<table id="tableB" border="1">
<tr>
<td>
B1
</td>
<td>
<input type="radio" name="b1" value="1" /> Yes
<input type="radio" name="b1" value="0" /> No
</td>
</tr>
<tr>
<td>
B2
</td>
<td>
<input type="radio" name="b2" value="1" /> Yes
<input type="radio" name="b2" value="0" /> No
</td>
</tr>
<tr>
<td>
B3
</td>
<td>
<input type="radio" name="b3" value="1" /> Yes
<input type="radio" name="b3" value="0" /> No
</td>
</tr>
</table>
<p>
<button id="submit">Submit</button>
<button id="reset">Reset</button>
</p>
CSS
html { margin: 10px; }
table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
table td { border: 3px solid #CCC; padding: 5px; }
table td:nth-child(1) { width: 75%; }
table td:nth-child(2) { text-align: center; }
h2 { font-size: 1.8em; font-weight; bold }
button { padding: 5px; border-radius: 15px; background-color: #CCC; width: 100px; }
JavaScript
window.ns = {};
ns.activeTable = null;
ns.validate = function() {
// Simple validation
// If we don't have 3 checked radio buttons, it is invalid
var checked = $("#" + ns.activeTable).find("input[type=radio]:checked");
var valid = (checked || []).length === 3;
$("#submit").prop("disabled", !valid);
return valid;
};
ns.validate();
$("#submit").click(function() {
var valid = ns.validate;
if (valid == false) {
alert("You must complete the form!");
return;
}
var results = $("#" + ns.activeTable).find("input[type=radio]:checked");
var output = ns.activeTable + " Results\n";
$.each(results, function(idx, data) {
output += "\t" + $(this).prop("name") +
" - " + $(this).val() + "\n";
});
alert(output);
});
$("#reset").click(function() {
$("input[type=radio]").prop("checked", false);
ns.activeTable = null;
ns.validate();
});
$("input[type=radio]").click(function() {
var selectedTable = $(this).closest("table");
if (ns.activeTable != null &&
selectedTable.prop("id") != ns.activeTable) {
alert("Invalid form selection. Onlye selections from " +
ns.activeTable + " are allowed");
$(this).prop("checked", false);
} else {
ns.activeTable = selectedTable.prop("id");
}
ns.validate();
});