Making sure form does not submit

I have a form here and some required fields, and you can see that some fields only become required depending on a selection the user makes so here is the form

<form>
    <table>
        <tr>
            <th colspan="8" style="font-size: 18px;">B. Car Information</th>
        </tr>
        <tr>
            <td colspan="2">
                Car Owner's Full Legal Name <span class="ast">*</span>
            </td>
            <td colspan="2">
                <label for="ownerFirstName">First:</label><br>
                <input type="text" id="ownerFirstName" name="ownerFirstName" required>
            </td>
            <td colspan="2">
                <label for="ownerMiddleName">Middle:</label><br>
                <input type="text" id="ownerMiddleName" name="ownerMiddleName">
            </td>
            <td colspan="2">
                <label for="ownerLastName">Last:</label><br>
                <input type="text" id="ownerLastName" name="ownerLastName" required>
            </td>
        </tr>
        <tr>
            <td>
                <div>Relationship to the Car Owner</div>
            </td>
            <td colspan="6">
                <input type="radio" name="relationship" value="Self"> Self <br>
                <input type="radio" name="relationship" value="Spouse"> Spouse <br>
                <input type="radio" name="relationship" value="Child"> Child <br>
                <input type="radio" name="relationship" value="Parent"> Parent <br>
                <input type="radio" name="relationship" value="Other" id="relationshipOther" placeholder="Enter reason here"> Other
                <!-- Added input field for other relationship -->
                <input type="text" id="otherRelationshipInput" name="otherRelationshipInput" style="display: none;" placeholder="Other Relationship Type">
            </td>
        </tr>
        <tr>
            <td colspan="2">
                Claimant's Full Legal Name (if different than car owner)
            </td>
            <td colspan="2">
                <label for="claimantFirstName">First:</label><br>
                <input type="text" id="claimantFirstName" name="claimantFirstName">
            </td>
            <td colspan="2">
                <label for="claimantMiddleName">Middle:</label><br>
                <input type="text" id="claimantMiddleName" name="claimantMiddleName">
            </td>
            <td colspan="2">
                <label for="claimantLastName">Last:</label><br>
                <input type="text" id="claimantLastName" name="claimantLastName">
            </td>
        </tr>
        <tr>
            <td colspan="6">
                Are you represented by an attorney?<span class="ast">*</span>
            </td>
            <td colspan="1">
                <input type="radio" id="attorneyYes" name="attorneyRepresentation" class="claimCheckbox" value="yes" required>Yes <br>
                <input type="radio" id="attorneyNo" name="attorneyRepresentation" class="claimCheckbox" value="no">No
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <div>Attorney Name (if applicable)</div>
            </td>
            <td colspan="4">
                <label for="attorneyFirstName">First Name:</label><br>
                <input type="text" id="attorneyFirstName" name="attorneyFirstName">
            </td>
            <td colspan="2">
                <label for="attorneyLastName">Last Name:</label><br>
                <input type="text" id="attorneyLastName" name="attorneyLastName">
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <div>Attorney Law Firm (if applicable)</div>
            </td>
            <td colspan="6">
                <label for="attorneyFirmName">Firm Name:</label><br>
                <input type="text" id="attorneyFirmName" name="attorneyFirmName">
            </td>
        </tr>
        <tr>
            <td colspan="8">If the Claimant is represented by an attorney, please provide the contact information for the attorney. The program will communicate with the attorney regarding this claim.</td>
        </tr>
        <tr>
            <td colspan="2">
                <div>Contact Information</div>
            </td>
            <td colspan="4">
                <label for="phone">Phone:</label><br>
                <input type="tel" id="phone" name="phone" pattern="[0-9]+" maxlength="15" title="Please enter only numbers" required onchange="removeNonNumericChars('phone')">
                <hr>
                <label for="email"><span class="ast">* </span>Email:</label><br>
                <input type="email" id="emailReg" name="emailReg" required>
            </td>


            <td colspan="1">
                <label for="workPhone">Work:</label><br>
                <input type="tel" id="workPhone" name="workPhone" pattern="[0-9]+" maxlength="15" onchange="removeNonNumericChars('workPhone')">
                <label for="mobilePhone">Mobile:</label><br>
                <input type="tel" id="mobilePhone" name="mobilePhone" pattern="[0-9]+" maxlength="15" onchange="removeNonNumericChars('mobilePhone')">
                <label for="homePhone">Home:</label><br>
                <input type="tel" id="homePhone" name="homePhone" pattern="[0-9]+"  maxlength="15" onchange="removeNonNumericChars('homePhone')">
            </td>
        </tr>
    </table>

    <table>
        <tr>
            <th colspan=" 8" style="font-size: 18px;">C. Car Claim Category</th>
        </tr>
        <tr>
            <th colspan="8" style="font-size: 18px;" class="subHeading">Accident Claims</th>
        </tr>
        <tr>
            <td colspan="4">
                Was the car involved in an accident? <span class="ast" required>*</span>
            </td>
            <td colspan="4">
                <input type="radio" id="accidentYes" name="accidentClaim" class="claimCheckbox" value="yes">Yes <br>
                <input type="radio" id="accidentNo" name="accidentClaim" class="claimCheckbox" value="no">No
            </td>
        </tr>
        <tr>
            <th colspan="8" style="font-size: 18px;" class="subHeading">Theft Claims</th>
        </tr>
        <tr>
            <td colspan="4">
                Was the car stolen? <span class="ast">*</span>
            </td>
            <td colspan="4">
                <input type="radio" value="yes" id="theftYes" name="theftClaim" class="claimCheckbox">Yes <br>
                <input type="radio" value="no" id="theftNo" name="theftClaim" class="claimCheckbox">No
            </td>
        </tr>
        <tr>
            <th colspan="8" style="font-size: 18px;" class="subHeading">Damage Claims</th>
        </tr>
        <tr>
            <td colspan="4">
                Was the car damaged due to natural calamities? <span class="ast">*</span>
            </td>
            <td colspan="4">
                <input type="radio" value="yes" id="damageYes" name="damageClaim" class="claimCheckbox">Yes <br>
                <input type="radio" value="no" id="damageNo" name="damageClaim" class="claimCheckbox">No
            </td>
        </tr>
    </table>
    <p>By clicking submit, you attest to and certify under penalty of perjury that all information provided in the above Registration Form is true and accurate and acknowledge that false statements may result in punishment.</p>
    <button type="submit" onclick="saveData(event)">Submit</button>
</form>

and here is the js

document.addEventListener("DOMContentLoaded", function () {
    // Get the "Yes" and "No" radio buttons
    var accidentYes = document.getElementById("accidentYes");
    var accidentNo = document.getElementById("accidentNo");
    var theftYes = document.getElementById("theftYes");
    var theftNo = document.getElementById("theftNo");
    var damageYes = document.getElementById("damageYes");
    var damageNo = document.getElementById("damageNo");

    // Get all other radio buttons
    const radioButtons = [
        accidentYes,
        accidentNo,
        theftYes,
        theftNo,
        damageYes,
        damageNo
    ];

    // Function to disable/enable radio buttons
    function toggleRadioButtons(disable) {
        radioButtons.forEach(function (radioButton) {
            radioButton.disabled = disable;
        });
    }

    // Add event listeners to the relevant radio buttons
    accidentYes.addEventListener("change", function () {
        toggleRadioButtons(accidentYes.checked);
    });

    accidentNo.addEventListener("change", function () {
        toggleRadioButtons(!accidentNo.checked);
    });

    theftYes.addEventListener("change", function () {
        toggleRadioButtons(theftYes.checked);
    });

    theftNo.addEventListener("change", function () {
        toggleRadioButtons(!theftNo.checked);
    });

    damageYes.addEventListener("change", function () {
        toggleRadioButtons(damageYes.checked);
    });

    damageNo.addEventListener("change", function () {
        toggleRadioButtons(!damageNo.checked);
    });
});

// Function to remove non-numeric characters from the phone input
function removeNonNumericChars(inputId) {
    let inputElement = document.getElementById(inputId);
    if (inputElement) {
        // Replace non-numeric characters with an empty string
        inputElement.value = inputElement.value.replace(/[^0-9]/g, '');
    }
}

// Attach the function to the phone input's onchange event
document.getElementById('phone').addEventListener('input', function () {
    removeNonNumericChars('phone');
});

// Attach the function to the workPhone input's onchange event
document.getElementById('workPhone').addEventListener('input', function () {
    removeNonNumericChars('workPhone');
});

// Attach the function to the mobilePhone input's onchange event
document.getElementById('mobilePhone').addEventListener('input', function () {
    removeNonNumericChars('mobilePhone');
});

// Attach the function to the homePhone input's onchange event
document.getElementById('homePhone').addEventListener('input', function () {
    removeNonNumericChars('homePhone');
});

// Function to toggle attorney fields based on selection
function toggleAttorneyFields() {
    const attorneyYes = document.getElementById("attorneyYes");
    const attorneyFirstName = document.getElementById("attorneyFirstName");
    const attorneyLastName = document.getElementById("attorneyLastName");
    const attorneyFirmName = document.getElementById("attorneyFirmName");
    const attorneyFirstNameLabel = document.querySelector('label[for="attorneyFirstName"]');
    const attorneyLastNameLabel = document.querySelector('label[for="attorneyLastName"]');
    const attorneyFirmNameLabel = document.querySelector('label[for="attorneyFirmName"]');

    var yesSelected = attorneyYes.checked;

    if (yesSelected) {
        attorneyFirstName.setAttribute('required', '');
        attorneyLastName.setAttribute('required', '');
        attorneyFirmName.setAttribute('required', '');

        if (!attorneyFirstNameLabel.innerHTML.includes('<span class="ast">*</span>')) {
            attorneyFirstNameLabel.innerHTML = '<span class="ast">*</span> ' + attorneyFirstNameLabel.innerHTML;
        }
        if (!attorneyLastNameLabel.innerHTML.includes('<span class="ast">*</span>')) {
            attorneyLastNameLabel.innerHTML = '<span class="ast">*</span> ' + attorneyLastNameLabel.innerHTML;
        }
        if (!attorneyFirmNameLabel.innerHTML.includes('<span class="ast">*</span>')) {
            attorneyFirmNameLabel.innerHTML = '<span class="ast">*</span> ' + attorneyFirmNameLabel.innerHTML;
        }
    } else {
        // If "Yes" is not selected, remove 'required' attribute from attorney's name and firm name fields
        attorneyFirstName.removeAttribute('required');
        attorneyLastName.removeAttribute('required');
        attorneyFirmName.removeAttribute('required');

        // Remove asterisks from attorney labels
        attorneyFirstNameLabel.innerHTML = attorneyFirstNameLabel.innerHTML.replace('<span class="ast">*</span>', '');
        attorneyLastNameLabel.innerHTML = attorneyLastNameLabel.innerHTML.replace('<span class="ast">*</span>', '');
        attorneyFirmNameLabel.innerHTML = attorneyFirmNameLabel.innerHTML.replace('<span class="ast">*</span>', '');
    }
}

// Add event listeners to the attorney radio buttons
document.getElementById("attorneyYes").addEventListener("change", function () {
    toggleAttorneyFields();
});

document.getElementById("attorneyNo").addEventListener("change", function () {
    toggleAttorneyFields();
});

// Function to toggle claimant name fields based on selection
function toggleClaimantNameFields() {
    var relationshipRadios = document.getElementsByName('relationship');
    var claimantFields = document.querySelectorAll('#claimantFirstName, #claimantMiddleName, #claimantLastName');
    var claimantLabels = document.querySelectorAll('label[for="claimantFirstName"], label[for="claimantMiddleName"], label[for="claimantLastName"]');
    // Check if "Self" is selected
    var selfSelected = false;
    for (var i = 0; i < relationshipRadios.length; i++) {
        if (relationshipRadios[i].checked && relationshipRadios[i].value === 'Self') {
            selfSelected = true;
            break;
        }
    }
    // Update the fields and labels accordingly
    if (selfSelected) {
        // If "Self" is selected, remove 'required' attribute from claimant's name fields
        claimantFields.forEach(function (field) {
            field.removeAttribute('required');
        });
        // Remove asterisks from claimant labels
        claimantLabels.forEach(function (label) {
            label.innerHTML = label.innerHTML.replace('<span class="ast">*</span>', '');
        });
    } else {
        // If "Self" is not selected, add 'required' attribute to claimant's name fields
        claimantFields.forEach(function (field) {
            field.setAttribute('required', '');
        });
        // Add asterisks to claimant labels if not already present
        claimantLabels.forEach(function (label) {
            if (!label.innerHTML.includes('<span class="ast">*</span>')) {
                label.innerHTML = '<span class="ast">*</span> ' + label.innerHTML;
            }
        });
    }
}

// Add event listeners to the relationship radio buttons
document.querySelectorAll('input[name="relationship"]').forEach(function (radio) {
    radio.addEventListener('change', function () {
        toggleClaimantNameFields();
    });
});

// Function to save form data
function saveData(event) {
    event.preventDefault();

    const requiredInputs = document.querySelectorAll('input[required], textarea[required], select[required]');

    // Check if any required field is empty
    let isEmpty = false;
    requiredInputs.forEach(input => {
        if (!input.value.trim()) {
            isEmpty = true;
        }
    });

  
    if (isEmpty) {
        alert("Please fill out all required fields.");
        return;
    }
}

This is what I tried with the js, but it seems that it still throws the error even when all fields are entered

const requiredInputs = document.querySelectorAll('input[required], textarea[required], select[required]');

    // Check if any required field is empty
    let isEmpty = false;
    requiredInputs.forEach(input => {
        if (!input.value.trim()) {
            isEmpty = true;
        }
    });

  
    if (isEmpty) {
        alert("Please fill out all required fields.");
        return;
    }

Again, I am looking for help so even when a user selects an option that makes new inputs required. When the user hits submit it should throw an error if those inputs are empty or buttonss not selected

Welcome to the forum @ash_food

Instead of using .forEach try using the .map method.

The other option is to place the required attribute in each of the input elements you want the submitter to fill in.

Also, your html does not specify what an asterisk means.

Happy coding

1 Like

Unfortunately, my form submission method ignores the required attribute and completes the action anyway

Try it without the JavaScript.

I have and thats why I am trying javascript now the required is ignored on my email input and radio buttons

I could not find the required attribute in the elements below.

this is basic html use ai to solve it

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.