remove required from input fields that are in hidden divs

user899119 picture user899119 · Nov 5, 2013 · Viewed 18.3k times · Source

I have one form and couple of divs with bunch of input fields, and one select field that shows one div and hide all others. In those input field I have html5 required tag. I would like to remove required tag from all input fields that are in hidden divs. How can I do that? Here is my js for show/hiding divs depending on my select options:

    <script>
function changeGroup(e) {
    /*
        1 - Remove all group classes
        2 - Add the currently selected group class
    */
    $("#main")
        .removeClass(allGroups)
        .addClass($("option:selected", e.target).val())     
}

/* 
    1 - Bind changeGroup function to "change" event
    2 - Fetch all group from the select field 
*/
var allGroups = $("select")
    .change(changeGroup)
    .find("option")
        .map(function() {
            return $(this).val();
        })
        .get()
        .join(' ');


</script>

Thank you for help... Dorijan

Answer

charlietfl picture charlietfl · Nov 5, 2013

Would use prop() method since required is a property. Once you remove the property then if user toggles so the become visible again have no current mechanism to track where they got removed.

For this reason I suggest you add a class requiredto all the inputs that have required property.

$('.required').prop('required', function(){
   return  $(this).is(':visible');
});

This will loop over all of the class required and adjust property based on visibility