I need to send form if all radio is true(it`s some like yes/no btns),or error if at least one false. There can be any number of such "Yes/No buttons". You need to send only if everything is "Yes", if at least 1 is not selected or "No", then do something else I try this
<form id="someForm">
<p>1-st group</p>
<div >
<div >
<input type="radio" name="radio1" value="conf">
</div>
<div >
<input type="radio" name="radio1" value="err" >
</div>
</div>
<p>2-nd group</p>
<div >
<div >
<input type="radio" name="radio2" value="conf">
</div>
<div >
<input type="radio" name="radio2" value="err">
</div>
</div>
<button id="test">go!</button>
</form>
$('#test').on('click', function(e) {
e.preventDefault();
$('#someForm')
.find('.radio-box input')
.each(function () {
inputs = $('input[type="radio"]');
if(inputs.is(':checked') && inputs.val() === 'conf')
{
console.log('form send');
}
else{
console.log('some is not checked');
}
});
});
hope to your help) thx!
CodePudding user response:
Check for inputs of type radio that are checked and hold a value of 'err'. If non are checked the size of find()
will be 0. Also check for yes answers if they match all radio options.
$('#someForm').on('submit', function(e) {
e.preventDefault();
const radio_no_answers = $(this).find('.radio-box input[type="radio"][value="err"]:checked');
const radio_yes_answers = $(this).find('.radio-box input[type="radio"][value="conf"]:checked');
if (radio_no_answers.length == 0 && radio_yes_answers.length == 2) {
console.log('submit');
} else {
console.log('err');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="someForm">
<p>1-st group</p>
<div >
<div >
<input type="radio" name="radio1" value="conf">Yes
</div>
<div >
<input type="radio" name="radio1" value="err">No
</div>
</div>
<p>2-nd group</p>
<div >
<div >
<input type="radio" name="radio2" value="conf">Yes
</div>
<div >
<input type="radio" name="radio2" value="err">No
</div>
</div>
<button type="submit">go!</button>
</form>
CodePudding user response:
if ( $('#someForm').find ('input[type=radio]:not(:checked)').length > 0 )
{
// handle error
}
else
{
$('#someForm').submit();
}