If you want to determine if a form can be submitted, use a submittable
method to check if required inputs have a value:
// update submit button
function submittable() {
// retrieve all required fields (needs to be done each time)
var $required = $('input[required=required]', '#form_process'),
$submittable = true;
$required.each(function() {
if ($(this).val()) {
// do nothing
} else {
$submittable = false;
}
});
return $submittable;
}
To make this work correctly, ensure that your universally required inputs have the required attribute and your optionally required address input does not have it.
<input name="fname" id="fname" placeholder="firstName" required="required">
<input name="lname" id="lname" placeholder="lastName" required="required">
<input name="address" id="address" placeholder="address">
Next is the validate
method which uses the submittable
function to validate the form and enable/disable the button accordingly:
var $submit = $('#submit');
// control validation
function validate() {
if (submittable()) {
// valid state
//alert('valid');
$submit.attr('disabled',false);
} else {
// invalid state
//alert('invalid');
$submit.attr('disabled',true);
}
}
Initially, run the validate
function:
// perform initial validation
validate();
Then, trigger it on keyup of any form input:
// validate on input keyup
$('#form_process input').keyup(function() {
validate();
});
You also need a function to get the currently checked radio option to show/hide additional input. Make sure to toggle the required attribute for the address input when needed so it's included in the validate
method:
var $address = $('#address'),
$server = $('#server');
function getChecked() {
// identify currently selected input
var $checked = $('input[name=client]:checked', '#form_process');
// if server is selected
if ($checked.attr('id') === 'server') {
//alert('server!');
$address.show();
$address.attr('required',true);
} else {
//alert('client!');
$address.hide();
$address.attr('required',false);
}
}
For this to function properly, set one of the radios as checked initially:
<input type="radio" name="client" id="client" value="TestClient" checked="checked">TestClient
<input type="radio" name="client" id="server" value="TestServer">TestServer
Call the getChecked
function at the beginning and whenever a radio selection changes (along with running the validate method):
// initial get checked call
getChecked();
// for each radio
$('input[type=radio]').each(function() {
// when selection changes
$(this).change(function() {
// get checked radio
getChecked();
// perform validation
validate();
});
});
note
This solution is specific to this particular problem. If you have more than 2 radios with different input scenarios, the getChecked()
function may require adjustment.
Additionally, $('input[type=radio]').each()
should be more targeted if there are multiple radio groups. In such cases, consider adding a class to each radio or wrapping them in a parent element to differentiate them.