I have some radio buttons that dynamically increase based on data. What I want is to check if all radio button are selected or not. If they're not, I want to show an error message on that particular row as I am using form substitution to send data to ajax.
$(document).ready(function() {
// radio buttons
$('#mySpan4').submit(function(e) {
e.preventDefault();
$.ajax({
url: 'ajax2.php',
data: $(this).serialize(), // reads the data ...
success: function(data) {
alert("data Updated Successfully");
window.location = 'login.html';
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="mySpan4">
<table>
<tr>
<td>
Name : abc
</td>
<td>
<input type="radio" name="game[0]" value="Mother">Mother
</td>
<td>
<input type="radio" name="game[0]" value="Father">Father
</td>
</tr>
<tr>
<td>
Name : def
</td>
<td>
<input type="radio" name="game[1]" value="Mother">Mother
</td>
<td>
<input type="radio" name="game[1]" value="Father">Father
</td>
</tr>
<tr>
<td>
Name : ghi
</td>
<td>
<input type="radio" name="game[2]" value="Mother">Mother
</td>
<td>
<input type="radio" name="game[2]" value="Father">Father
</td>
</tr>
</table>
<input name="submit" type="submit" id="submit" value="submit">
</form>
You may try using :checked
var all = $('input[type=radio][name^=game]').length;
var chk = $('input[type=radio][name^=game]:checked').length;
var exp = all / 2;// in a group two radios each, any one will be selected
if(chk === exp) {
//all checked
} else {
// some goup is not checked
}
$(document).ready(function() {
// radio buttons
$('#mySpan4').submit(function(e) {
e.preventDefault();
var all = $('input[type=radio][name^=game]').length;
var chk = $('input[type=radio][name^=game]:checked').length;
var exp = all / 2; // in a group two radios each, any one will be selected
if (chk !== exp) {
alert('Error, select all !');
return false;
}
$.ajax({
url: 'ajax2.php',
data: $(this).serialize(), // reads the data ...
success: function(data) {
alert("data Updated Successfully");
window.location = 'login.html';
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="mySpan4">
<table>
<tr>
<td>
Name : abc
</td>
<td>
<input type="radio" name="game[0]" value="Mother">Mother
</td>
<td>
<input type="radio" name="game[0]" value="Father">Father
</td>
</tr>
<tr>
<td>
Name : def
</td>
<td>
<input type="radio" name="game[1]" value="Mother">Mother
</td>
<td>
<input type="radio" name="game[1]" value="Father">Father
</td>
</tr>
<tr>
<td>
Name : ghi
</td>
<td>
<input type="radio" name="game[2]" value="Mother">Mother
</td>
<td>
<input type="radio" name="game[2]" value="Father">Father
</td>
</tr>
</table>
<input name="submit" type="submit" id="submit" value="submit">
</form>