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>
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>
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&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>
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!
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>
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>
Related
I have a problem with my JavaScript Code...
I'm developing a "ToDo-List", where you can add and remove Elements all of these things are already working but I also like to have an "counter" which shows the number (length) of all unchecked checkboxes.
I have created a button with JS:
let btn = document.createElement("button");
btn.classList.add("destroy");
and I already have saved the right place for show the number (length) for the unchecked checkboxes:
let counter = document.getElementsByClassName("todo-count");
and then i wrote code to show me the unclicked boxes:
for(let btn of buttons) {
if(btn.classList.contains("destroy")) {
btn.addEventListener("click", function() {
btn.parentElement.parentElement.remove();
for(let counts of counter) {
let parsed = parseInt(counts.innerText);
counts.innerText = parsed - 1;
}
})
}
}
As already mentioned, adding elements already works, but as soon as I add e.g. 5 elements and the first element (which, like all other elements, also has a checkbox) is calculated as minus 5 instead of minus 1...
Just count the checked checkboxes, do not try to maintain the state.
function updateCounts() {
const allCheckboxes = document.querySelectorAll(".my-class");
const checkedCheckboxes = document.querySelectorAll(".my-class:checked");
console.log("Checked count:", checkedCheckboxes.length);
console.log("Unchecked count:", allCheckboxes.length - checkedCheckboxes.length);
}
updateCounts();
document.querySelector("form").addEventListener("change", updateCounts);
<form>
<input type="checkbox" class="my-class">
<input type="checkbox" class="my-class">
<input type="checkbox" class="my-class">
<input type="checkbox" class="my-class">
</form>
"...but when I click a checkbox, the counter should subtract by one."
You'll need another event listener for the change event. The change event fires off when the user changes the value of a form control and then clicks elsewhere (which is another event like blur or focusout).
If you haven't already, wrap everything in a <form> so you can use the HTMLFormElement interface. It's very terse and specialized for forms and form controls. Bind your event handler to the form so you can have the advantages Event Delegation will give you like listening for events for an unlimited number of elements whether they are static or dynamically added.
const uncheckedCount = e => {
const io = e.currentTarget.elements;
const out = io.out;
if (e.target.name === 'btn' || e.type === 'change') {
const unchecked = [...io].filter(inp => inp.checked === false)
out.value = unchecked.length;
}
};
const ui = document.forms[0];
ui.addEventListener('change', uncheckedCount);
ui.addEventListener('click', uncheckedCount);
<form>
<input type='checkbox' checked>
<input type='checkbox' checked>
<input type='checkbox'>
<input type='checkbox' checked>
<input type='checkbox'>
<input type='checkbox' checked>
<input type='checkbox'>
<input type='checkbox'>
<input type='checkbox'>
<input type='checkbox'>
<input type='checkbox' checked>
<br>
<button name='btn' type='button'>GO</button>
<output name='out'></output>
</form>
I was wondering if there was a better way to go about enabled/disabled multiple checkboxes at once.
In the html I have two radio buttons to choose between all hair options and custom hair options, having the default all one disable the checkboxes while the custom one enables them.
This is what I've got so far that works (probably looks dumb, I apologize), but I'd like to know if there's a more efficient way to go about this? I'd like to do it as "small" as possible while still being easily readable/understandable for my own sake.
function checkHaOp(){
if (document.getElementById("hairOptionAll").checked){
document.getElementById("hairAuburn").disabled = true;
document.getElementById("hairBlack").disabled = true;
document.getElementById("hairBlonde").disabled = true;
document.getElementById("hairBrown").disabled = true;
document.getElementById("hairRed").disabled = true;
document.getElementById("hairOther").disabled = true;
}
else if (document.getElementById("hairOptionCustom").checked){
document.getElementById("hairAuburn").disabled = false;
document.getElementById("hairBlack").disabled = false;
document.getElementById("hairBlonde").disabled = false;
document.getElementById("hairBrown").disabled = false;
document.getElementById("hairRed").disabled = false;
document.getElementById("hairOther").disabled = false;
}
}
Preferably using javascript since I don't know jquery.
I'd also appreciate explanations of things since I am still learning.
You can add/use class like said #NiettheDarkAbsol
then something like that.
var inpck = document.getElementsByClassName("input-checkbox");
if (document.getElementById("hairOptionAll").checked) {
for(var i = 0; i < inpck.length; i++) {
inpck[i].disabled = true;
}
}
if (document.getElementById("hairOptionCustom").checked) {
for(var i = 0; i < inpck.length; i++) {
inpck[i].disabled = false;
}
}
Now your turn to refactor this :D
You can use
document.querySelectorAll('[id^=hair]')
It selects all elements that has an id which starts with "hair"
<!DOCTYPE html>
<html>
<body>
<input type="checkbox" id="hairOptionAll">
<input type="checkbox" id="hairAuburn">
<input type="checkbox" id="hairBlack">
<input type="checkbox" id="hairBlonde">
<input type="checkbox" id="hairBrown">
<input type="checkbox" id="hairRed">
<input type="checkbox" id="hairOther">
</body>
<script>
const hairCb = document.querySelectorAll('[id^=hair]');
for (let i=0; i<hairCb.length; i++) {
hairCb[i].disabled = true;
}
</script>
</html>
Here's the optimized solution.
<div class="radio-btns">
All <input type="radio" id="hairOptionAll" name="hairOptionAll"/>
Custom <input type="radio" id="hairOptionCustom" name="hairOptionCustom"/>
</div>
<div class="hairOptions">
hairAuburn <input type="checkbox" id="hairAuburn" />
hairBlack <input type="checkbox" id="hairBlack" />
hairBlonde <input type="checkbox" id="hairBlonde" />
hairBrown <input type="checkbox" id="hairBrown" />
hairRed <input type="checkbox" id="hairRed" />
hairOther <input type="checkbox" id="hairOther" />
</div>
<script type="text/javascript">
const radioBtns = document.querySelector('.radio-btns');
radioBtns.children[0].checked = true;
radioBtns.addEventListener("click", (event) => {
radioBtns.children[0].checked = (event.target.id == 'hairOptionAll') ? true : false;
radioBtns.children[1].checked = (event.target.id == 'hairOptionCustom') ? true : false;
const allOptions = [...event.target.parentElement.nextElementSibling.children];
allOptions.map(option => ( option.checked = (event.target.id == 'hairOptionCustom') ? true : false ) );
});
</script>
Here is a complete working code you. To minimise the code we write to we need to use a class selector not an id - Give the same class to your radio button and then use a forEach loop to go through all the radio button. Add the class to your checkboxes as well.
To get all the checkboxes we can use forEach method.
Once you have all the radio button you need to listen for a change on a particular radio button and then we will check whether the radio button we have selected is checked and its id is all or custom.
To get the id of the actual radio button which was clicked we can use getAttribute method which return the id of checked radio button.
If our condition matches we will disable all the checkboxes or if its else then we enable all the checkboxes using forEach loop on the checkbox classes.
We will pass true or false as an argument to disable checkboxes function to avoid having have two loops
Live Working Example (I have added notes / comment on each line of code for your understanding as well)
//Enable disable checkbox
function disableChekbox(isChecked) {
let getHairOptions = document.querySelectorAll('.hairOptions') //get all checkboxes
getHairOptions.forEach(function(x) {
x.disabled = isChecked
})
}
let getHairRadio = document.querySelectorAll('.hairOptionAll') //get all radio buttons
//For each all radio buttons
getHairRadio.forEach(function(radio) {
//listen to change on radio
radio.addEventListener('change', function(e) {
if (e.target.checked && e.target.getAttribute('id') == 'hairOptionAll') {
//loop through all checkboxes
disableChekbox(true)
} else if (e.target.checked && e.target.getAttribute('id') == 'hairOptionCustom') {
//loop through all checkboxes
disableChekbox(false)
}
})
})
All <input type="radio" id="hairOptionAll" name="hairOptionAll" class="hairOptionAll" />
Custom <input type="radio" id="hairOptionCustom" name="hairOptionAll" class="hairOptionAll" />
<br>
<br>
hairAuburn <input type="checkbox" id="hairAuburn" class="hairOptions" />
hairBlack <input type="checkbox" id="hairBlack" class="hairOptions" />
hairBlonde <input type="checkbox" id="hairBlonde" class="hairOptions" />
hairBrown <input type="checkbox" id="hairBrown" class="hairOptions" />
hairRed <input type="checkbox" id="hairRed" class="hairOptions" />
hairOther <input type="checkbox" id="hairOther" class="hairOptions" />
i'm basically JavaScript newbie and I'm trying to resolve this problem of mine for quite a while. So,i'm doing JS school project and I need to make connection between checkbox and text form. If checkbox is not checked, text form should be disabled and vice versa. This is piece of code I have written:
function cbtf() {
if (document.getElementById('checkbox').checked==false) {
document.getElementById('textform').disabled=true;
}
}
Can anyone write a new code ? That would be much of a help.
Simply attach a method to checkbox's onclick handler:
function enableElement(id, enable) {
document.getElementById(id).disabled=!enable;
}
<label>
<input
type="checkbox"
onclick="enableElement('textform', this.checked)"
/>
ENABLE
</label>
<br/>
<textarea id="textform" style="width:100%; height:200px" disabled>
THIS IS TEXTAREA WITH ID "textform"
</textarea>
or another simplification without creating special one-liner method - just define Your will directy in onclick event:
<label>
<input
type="checkbox"
onclick="document.getElementById('textform').disabled = !this.checked"
/>
ENABLE
</label>
<br/>
<textarea id="textform" style="width:100%; height:200px" disabled>
THIS IS TEXTAREA WITH ID "textform"
</textarea>
You can add a click event to the checkbox, and assign it's check state to the disabled property of the TextBox.
document.querySelector('input[type=checkbox]').onclick = function(e) {
document.querySelector('input[type=text]').disabled = e.target.checked;
};
<input type="checkbox" name="">
<input type="text" name="">
You won't get that to work unless you attach an event to the checkbox, so I would suggest something like this:
var textbox = document.getElementById('textform');
var checkbox = document.getElementById('checkbox');
checkbox.addEventListener("change", function() {
if (checkbox.checked) {
textbox.disabled = false;
} else {
textbox.disabled = true;
}
})
I've read variations on this for a few days and can't find a working solution to what I want. And it's probably easier than I'm making out.
I have a set of radio buttons, and want to pass the checked value to part of a URL.
<input type="radio" name="link" value="one" checked="checked">One
<input type="radio" name="link" value="two">Two
<input type="radio" name="link" value="three">Three
And I want the value of whichever one is checked to be passed to a variable such as
dt which then passes to the Submit button which takes you to a url that includes text from the radio buttons.
<input type="button" value="OK" id="ok_button" onclick="parent.location='/testfolder/' + dt;>
But I'm struggling to find out how to get
var dt = document.getElementByName('link').value;
to work for me when I try and apply a for loop to make sure it's checked.
Does my onclick='parent.location.... in the submit button need to be in a function rather than part of the submit button? So the same function can grab the value of the radio button?
So I'm appealing to StackOverflowers for hopefully a bit of guidance... Thanks
First of you want to know which value your combobox has with this easy to use on-liner.
document.querySelector('[name="link"]:checked').value;
I suggest using event handlers to handle the javascript, so don't write it in the onclick attribute.
var btn = document.getElementById('ok_button');
btn.addEventListener('click', function(){ /*handle validations here*/ })
jsfiddle
you can try below code
<input type="button" value="OK" id="ok_button" onclick="functionName();'>
JavaScript Code
<script type="javascript">
function functionName(){
var radios = document.getElementsByName('link'),
value = '';
for (var i = radios.length; i--;) {
if (radios[i].checked) {
value = radios[i].value;
break;
}
}
window.location.href='/testfolder/'+ value
}
</script>
var dt = document.getElementsByName('link')[0].value works for me
you can use it in either the inline onclick handler or a function you define
<input type="radio" id="1" name="link" onchange="WhatToDo()" value="one">One</input>
<input type="radio" id="2" name="link" onchange="WhatToDo()" value="two">Two</input>
<input type="radio" id="3" name="link" onchange="WhatToDo()" value="three">Three</input>
<script type="text/javascript">
function WhatToDo() {
var rButtons = document.getElementsByName('link');
for (var i = 0; i < rButtons.length; i++) {
if (rButtons[i].checked) {
alert(rButtons[i].value);
}
}
}
</script>
Maybe something like this. Use onchange and then loop through your radio buttons. Whilst looping look to see if the radio button is checked. Its a starting point.
I am using this javascript code. and on button click I want that atleast one checkbox selection is required. do anyone have idea what I am doing wrong. I don't want to use jquery.
function check()
{
var flag = false;
for(var i=1;i<=4;i++)
{
var checkb = document.getElementById("check"+i);
if(checkb.checked)
{
flag = true;
break;
}
}
if(!flag)
alert("What is your interest \n(select at least one option)");
return flag;
}
</script>
Button Click Code is
<input type="submit" name="submit" value="Submit" onclick="return check();">
The code works fine. Do hou have id="check1" set on your checkbox tags?
Yes, your code works fine as noted by the comments above. However, you could do your check for...checks a little more cleanly - you're expecting "check0" - "check4" for the IDs. You could just grab them all and not worry about a set limit (odds are your code isn't working because at least one of the IDs you're using doesn't exist).
<input type="checkbox" id="check0" />
<input type="checkbox" id="check1" />
<input type="checkbox" id="check2" />
<input type="checkbox" id="check3" />
<hr/>
<input type="button" onclick="checkIt();" value="Check the Checks">
And some JS:
checkIt = function()
{
var checks = document.getElementsByTagName('input');
var hasCheck = false;
for(i in checks)
{
// Could also check for a classname here to narrow
// your result set.
if(checks[i].type == 'checkbox')
hasCheck |= checks[i].checked;
}
if(!hasCheck)
alert('You should check one!');
return hasCheck;
}