Search code examples
htmlformsinputrequired

Can´t submit form because of required inputs of my blocked div


I need to submit a form but some of inputs on my blocked div are required.

When I click "No" and then on submit can't submit, I think it's due to required inputs of my "div1".

What I supose to do to to remove required inputs when "div1" is blocked?

Here's my code:

<!DOCTYPE html>
<html>
<body>
<script>
function show2(){
  document.getElementById('div1').style.display = 'block';
}
function show1(){
  document.getElementById('div1').style.display = 'none';
}
	  </script>
<form action="/action_page.php">
 	<input type="radio" name="C" value="Yes" onclick="show2();" required> Yes <br>
  	<input type="radio" name="C" value="No" onclick="show1();" required> No <br>
    
    
    <div id="div1" class="div1" style="display:none;">
	<hr>
	<h4>Div1</h4>
	<input type="radio" name="V" value="Yes"  required> Yes <br>
	<input type="radio" name="V" value="No"  required> No <br>
	
	</div>
  <input type="submit">
</form>
</body>
</html>


Solution

  • Are you looking to set the required status of input fields dynamically?

    Hope this approach works.

    1. Declare the option input fields (fields under id div1) as non mandatory fields.
    2. On the radio button change, update the validity of the input field dynamically.

    <form action="/action_page.php">
        <input type="radio" name="C" value="Yes" onclick="show2();" required> Yes <br>
        <input type="radio" name="C" value="No" onclick="show1();" required> No <br>
    
    
        <div id="div1" class="div1" style="display:none;">
            <hr>
            <h4>Div1</h4>
            <input type="radio" name="V" value="Yes"> Yes <br>
            <input type="radio" name="V" value="No"> No <br>
    
        </div>
        <input type="submit">
    </form>
    <script>
        function show2() {
            document.getElementById('div1').style.display = 'block';
            setFiledValidity(true);
        }
    
        function show1() {
            document.getElementById('div1').style.display = 'none';
            setFiledValidity(false);
        }
    
        function setFiledValidity(validityStatus) {
            const inputs = document.getElementById('div1').getElementsByTagName('input');
            for (let index = 0; index < inputs.length; index++) {
                // Setting validity
                inputs[index].required = validityStatus;
            }
        }
    
        // Initializing 
        setFiledValidity(false);
    </script>

    Hope this is the solution that you are looking for.