Are there alternative methods, such as using JavaScript, to hide form fields in PHP templates without causing validation issues?

When hiding form fields in PHP templates using CSS or other methods, the fields may still be submitted and cause validation issues. One alternative method to hide form fields without causing validation problems is to use JavaScript to dynamically show or hide the fields based on user interaction. This way, the fields are not submitted unless they are visible and interacted with by the user.

<!-- PHP template code -->
<form method="post" action="submit_form.php">
    <input type="text" name="username" id="username">
    <input type="password" name="password" id="password">
    <button type="button" onclick="toggleFields()">Show/Hide Fields</button>
    <input type="submit" value="Submit">
</form>

<script>
function toggleFields() {
    var usernameField = document.getElementById('username');
    var passwordField = document.getElementById('password');
    
    if (usernameField.style.display === 'none') {
        usernameField.style.display = 'block';
        passwordField.style.display = 'block';
    } else {
        usernameField.style.display = 'none';
        passwordField.style.display = 'none';
    }
}
</script>