skip to Main Content

I have the following code on my web page:

<form>

    <input type="checkbox" id="myCheckbox2" />
   first: <input type="text" id="fname" name="fname" >
    <input type="text" />
    Last:<input type="text" id="lname" name="lname">
    <button type="submit">Submit</button>
</form>

when the user clicks on the checkbox with Id= myCheckbox2 then I want the input box fname and lname to be required. I have several other checkboxes and text boxes on my page so i want to get the input box by the id. Below is what I tried:

<script>

    var $myCheckbox = $('#myCheckbox2'),
      $(document).ready(function() {
    $('.checkbox').change(function() {
        if ($('.inputBox').attr('required')) {
           $('.inputBox').removeAttr('required');
        } 
        else {  
           $('.inputBox').attr('required','required');
        }
    });
});


</script>

the above code is making all the input boxes to be required.

2

Answers


  1. You can just use change event on the required checkbox and for adding required to your inputs you can use $('[name=lname],[name=fname]').prop('required', $(this).is(':checked'));

    Demo Code:

    $('#myCheckbox2').change(function() {
      $('[name=lname],[name=fname]').prop('required', $(this).is(':checked'));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form>
    
      <input type="checkbox" id="myCheckbox2" /> first: <input type="text" id="fname" name="fname">
      <input type="text" /> Last:
      <input type="text" id="lname" name="lname">
      <button type="submit">Submit</button>
    </form>
    Login or Signup to reply.
  2. Pleas try this code:

    <form>
    
        <input type="checkbox" id="myCheckbox2" />
       first: <input type="text" id="fname" class="namefamily" name="fname" >
        <input type="text" />
        Last:<input type="text" id="lname" class="namefamily" name="lname">
        <button type="submit">Submit</button>
    </form>
    </body>
    </html>
    <script> 
       $(function(){
        $('#myCheckbox2').on('click',function() {
            if($(this).is(':checked')){
            
                $('.namefamily').attr('required','required');
            }else{
            
                $('.namefamily').removeAttr('required');
            }
             
        });
    }); 
     
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search