Home > Software design >  Disable button if one of the checkboxes are not checked
Disable button if one of the checkboxes are not checked

Time:10-01

I have two checkboxes in HTML called accepttermsandcond-checkbox and accepttermsandcond-checkbox and I made a Button called startusing-button

I want the startusing-button to stay disabled, if one of these checkboxes are not checked.

The problem is that it disables it right now in the beginning, but if I check both, it doesn't enable the button.

Note: even if I add document.getElementById('startusing-button').disabled = false; to the code it doesn't solve the issue

How could I make the button to be enabled only if both of the checkboxes are checked?

Edit: I forgot to mention that I have a lot of checkboxes and buttons. It would be ideal if the solution only affected these two checkboxes with one button, leaving the rest of the checkboxes and buttons alone.

    var ebpDocumentCheckboxid = document.getElementById('document-checkboxid');
    var ebpAcceptTermsandCondCheckbox =document.getElementById('accepttermsandcond-checkbox');

            if (ebpDocumentCheckboxid.checked && ebpAcceptTermsandCondCheckbox.checked) { 
              
            }
            else {
                document.getElementById('startusing-button').disabled = true;

            }
<input type="checkbox" id="document-checkboxid"/>
<input type="checkbox" name="VAT" id="accepttermsandcond-checkbox"/>


<button type="button" id="startusing-button">CreateSubscription</button>

CodePudding user response:

If i understood you correct you want the button to be only enabled when both checkboxes are checked, right? If so you could try something like this:

var ebpDocumentCheckboxid = document.getElementById("document-checkboxid");
var ebpAcceptTermsandCondCheckbox = document.getElementById(
  "accepttermsandcond-checkbox"
);
var btn = document.getElementById("startusing-button");

const onCheckboxChanged = ()=>{
  btn.disabled = (!ebpDocumentCheckboxid.checked) || (!ebpAcceptTermsandCondCheckbox.checked);
}

ebpDocumentCheckboxid.onchange = onCheckboxChanged;
ebpAcceptTermsandCondCheckbox.onchange = onCheckboxChanged;

I also added disabled="true" to the button so its disabled from the start.

Here is a codepen of a working example: https://codepen.io/jonas_weinhardt/pen/QWgoGzL?editors=1010

Edit:

You should probably use Nitheesh answer because its a much simpler and general approach!

CodePudding user response:

Try this code, more simple and readable(I hope).

(()=>{
    let checkboxes = [
        document.querySelector('#document-checkboxid'),
        document.querySelector('#accepttermsandcond-checkbox')
    ];
    let button = document.querySelector('#startusing-button');

    for(let checkbox of checkboxes) {
        checkbox.addEventListener('click', changeStatus); // changeStatus function onclick
    }

    changeStatus(); // run changeStatus function automatically

    function changeStatus(){
        if(checkboxes.every(checkbox => checkbox.checked)) button.removeAttribute('disabled');
        else button.setAttribute('disabled', 'true');
    }
})();
<input type="checkbox" id="document-checkboxid"/>
<input type="checkbox" name="VAT" id="accepttermsandcond-checkbox"/>


<button type="button" id="startusing-button">CreateSubscription</button>

CodePudding user response:

try this,

i add value "disabled" to button and create two onclick method to get .checked status, and if both are true change button parameter "disabled=true" to "disabled=false"

<!DOCTYPE html>

<head>
</head>

<body>
  
<div id = "test">
<input type="checkbox" id="document-checkboxid" onclick="firstchb()"/>
<input type="checkbox" name="VAT" id="accepttermsandcond-checkbox" onclick="secondchb()"/>


<button type="button" id="button" disabled >CreateSubscription</button>
  
</div>

</body>
<script>

let ebpDocumentCheckboxid = null;
let ebpAcceptTermsandCondCheckbox = null;
function firstchb(){
ebpDocumentCheckboxid = document.getElementById('document-checkboxid').checked;
enableit();
}

function secondchb(){
ebpAcceptTermsandCondCheckbox = document.getElementById('accepttermsandcond-checkbox').checked;

enableit();
}
function enableit(){
  if (ebpDocumentCheckboxid == true && ebpAcceptTermsandCondCheckbox == true) { 
              document.getElementById('button').disabled = false;
              
            }
            else {
                document.getElementById('button').disabled = true;

            }
}
            
</script>
</html>

CodePudding user response:

EDIT#2: I updated the answer to have coverage both for required and optional checkboxes, as requested in comments.

EDIT: just noticed it still can be accessed with keyboard tab focus and fire the event. So not a perfect solution, note this.

This can be done with plain CSS:

button {
  padding: 10px;
}

input[required]:not(:checked) ~ button {
  background-color: #b0b0b0;
  color: #d0d0d0;
  border: 1px outset #808080;
  pointer-events: none;
}
<form>
  <label>ID:</label>
  <input type="checkbox" id="document-checkboxid" required />
  <label>T&amp;C</label>
  <input type="checkbox" name="VAT" id="accepttermsandcond-checkbox" required />
  <hr />
  <label>Something irrelevant:</label><input type="checkbox" name="optional_one" id="something" />
  <label>Also optional:</label><input type="checkbox" name="optional_two" id="something else" />
  <hr />
  <button type="submit" id="startusing-button">CreateSubscription</button>
</form>

CodePudding user response:

You have to trigger change of checkboxes.

Simply checking both checkboxes have checked or not, will work only on the loading of document. You have to repeat this process each time the checkbox status is changed.

I have modified your script a little bit.

Logic

  • Select all checkboxes using document.querySelectorAll('input[type="checkbox"]').
  • Add a change event on checkbox by looping this list using forEach.
  • Inside the change event, find the count of selected checkboxes.
  • If that matches to the length of total check box, enable the button, or disable it.

const checkBoxes = document.querySelectorAll('input[type="checkbox"]');
const submitButton = document.getElementById('startusing-button');
checkBoxes.forEach((cb) => {
  cb.addEventListener('change', checkButtonStatus);
});
function checkButtonStatus() {
  const checkedCount = [...checkBoxes].filter((cb) => cb.checked);
  submitButton.disabled = checkedCount.length !== checkBoxes.length
}
checkButtonStatus();    
<input type="checkbox" id="document-checkboxid" />
<input type="checkbox" name="VAT" id="accepttermsandcond-checkbox" />

<button type="button" id="startusing-button">CreateSubscription</button>

Edit:

If you want to select only the two checkboxes, you can handle this in multiple ways. You can use some custom attribute with some unique value. Here in the below example I use identifier="my-custom-identifier" and make the inputs selection with document.querySelectorAll('input[identifier="my-custom-identifier"]'). This will check for all input elements with the identifier having value my-custom-identifier.

Why I use this approach is to make your solution a little more generic. You just have to use identifier="my-custom-identifier" in all inputs where you want to include for this checking.

Working Fiddle

const checkBoxes = document.querySelectorAll('input[identifier="my-custom-identifier"]');
const submitButton = document.getElementById('startusing-button');
checkBoxes.forEach((cb) => {
  cb.addEventListener('change', checkButtonStatus);
});
function checkButtonStatus() {
  const checkedCount = [...checkBoxes].filter((cb) => cb.checked);
  submitButton.disabled = checkedCount.length !== checkBoxes.length
}
checkButtonStatus();
<input type="checkbox" id="document-checkboxid" identifier="my-custom-identifier" />
<input type="checkbox" name="VAT" id="accepttermsandcond-checkbox" identifier="my-custom-identifier" />
<button type="button" id="startusing-button">CreateSubscription</button>

If you still want to make use of only 2 element by picking them with id, you could select them using ids. Like document.querySelector('input[id="document-checkboxid"]') and document.querySelector('input[id="accepttermsandcond-checkbox"]') and bind change event to them. Inside the change event, check whether both are checked inside the change function.

Working Fiddle

const checkBox1 = document.querySelector('input[id="document-checkboxid"]');
const checkBox2 = document.querySelector('input[id="accepttermsandcond-checkbox"]');
const submitButton = document.getElementById('startusing-button');

checkBox1.addEventListener('change', checkButtonStatus);
checkBox2.addEventListener('change', checkButtonStatus);

function checkButtonStatus() {
  const allChecked = checkBox1.checked && checkBox2.checked;
  submitButton.disabled = !allChecked;
}
checkButtonStatus();
<input type="checkbox" id="document-checkboxid" />
<input type="checkbox" name="VAT" id="accepttermsandcond-checkbox" />
<button type="button" id="startusing-button">CreateSubscription</button>

  • Related