Home > Enterprise >  Jquery with toggle , add "required" attribut into input field when div visible and remove
Jquery with toggle , add "required" attribut into input field when div visible and remove

Time:01-22

i'm new with jquery and i have a problem with my codes, i would make the checkbox as a toggle with jquery, and when the checkbox "clicked" and the toggle shows the div, then add required attribut into the checkbox input, and when it "clicked" again and the toggle is hidden then remove the required attribut. But when in the third "click" the toggle is show up but not adding required attribut into the checkbox input,

And I want the code to continue to run like that logic.

Here is my codes
HTML

  <div >
                            <div >
                              <label for="checkbox1"  id="les">
                                <input type="checkbox" id="checkbox1" name="user">
                                <div ></div>
                              </label>
                             
                            </div>
                          </div>
                          <div id="exmImg" style="display: none">
                            <label for="expImg" >Contoh Gambar</label><br>
                            <img src="/imgs/mb.jfif" alt=""  ><br>
                            <label for="gmb"  id="szz">
                              Upload file
                            </label>
                            <input type="file"  name="exmImg" id="gmb">
                          </div>

SCRIPT
  <script>
                            
                            $(document).ready(function(){
                              $("#checkbox1").click(function(){
                                $("#exmImg").toggle("fast");
                                $("#gmb").attr("required", true);

                                $("#checkbox1").click(function(){
                                      $("#gmb").removeAttr("required");
                                    });
                              });
                            });
                      
          
  </script>

Thanks you guys...

CodePudding user response:

Toggling the required property of the #gmb element should do the trick.

$(document).ready(function () {
    $("#checkbox1").click(function () {
        $("#exmImg").toggle("fast");
        let gmb = $("#gmb").get(0);
        gmb.required = !gmb.required;
    });
});

CodePudding user response:

 $(document).ready(function(){                   
       $("#checkbox1").change(function(e){              $ 
          ("#exmImg").toggle("fast");            
          if(e.target.checked) {             
            $("#exmImg").css("display","block");               
            $("#gmb").attr("required", true);
          } else{                                  
            $("#exmImg").css("display","none");  
            $("#gmb").removeAttr("required");
          }
       });
});
  • Related