Search code examples
javascriptform-databootstrap-5

Bootstrap 5 disabled+checked switch ignored by JS FormData class


I have a Bootstrap 5 switch input which I want to make mandatory (checked by default and not uncheckable). The documentation says you can combine the attributes checked and disabled. However, the Javascript FormData class seems to ignore disabled inputs, regardless if they are checked. Is there a workaround or can't I use FormData?


Solution

  • The vanilla Javascript solution is to populate the FormData object by hand:

    let form = e.target;
    let data = new FormData(form); // Serialize all form elements that are not disabled
    
    // Find all disabled Bootstrap switches ...
    let switchInputs = form.querySelectorAll('.form-switch>input[type=checkbox]:disabled');
    
    // ... and append them to the FormData object
    switchInputs.forEach(function(input){
        if(input.checked) {
           data.append(input.name, input.value || 'on');   
        }
    });