Enable or disable target element based on checkbox checked state - javascript

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;
}
})

Related

Disable button if one of the checkboxes are not checked

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>

Run function after a checkbox change on my page

I have dynamically created check boxes on my page and assigned each of them an unique id like 'renameteam1', 'renameteam2' etc.. I am trying to run a function when one of these gets checked. The function will then allow the user to enter a corresponding field that was previously readonly.
I have tried the following but it doesn't seem to be working.
var a=0;
$('input[type=checkbox]').change(function () {
for (var i=0;i<rows3;i++){
a=a+1;
var id= '#renameteam'+a;
if ($(id).is(":checked")) {
$('#newname'+a).removeProp('readonly');
}
}
//Here do the stuff you want to do when 'unchecked'
});
Any Suggestions?
This is how I would do it
//delegate the event so you can call this on document ready and it will still be bound to any dynamically created elements
$(document).on('change', 'input[type=checkbox]', function() {
var checkbox = $(this),
otherInput = $('#' + checkbox.data('id'));
otherInput.prop('readonly', !checkbox.is(':checked'));
if (!checkbox.is(':checked')) {
// do stuff here when checkbox isn't checked - not sure if you still want this bit but it is as per your comments in the code above
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" value="" id="renameteam1" data-id="newname1" />
<!-- use a data attribute to target the id of the input you want to make readonly -->
<input type="textbox" name="textbox" value="" id="newname1" readonly />
If you don't want to use a data attribute, you could do this:
//delegate the event so you can call this on document ready and it will still be bound to any dynamically created elements
$(document).on('change', 'input[type=checkbox]', function() {
var checkbox = $(this),
otherInput = $('#newname' + this.id.replace('renameteam', ''));
otherInput.prop('readonly', !checkbox.is(':checked'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" value="" id="renameteam1" />
<!-- use a data attribute to target the id of the input you want to make readonly -->
<input type="textbox" name="textbox" value="" id="newname1" readonly />
Try using an on click instead of on change for checkboxes and radio buttons.

How to hide radio button until something happens?

So I want to hide a radio button until my form is filled out but I don't know how. I tried .hide(); and that worked when I put it outside of my .submit function but doesn't work inside of it. This is using jquery and bootstrap.
Here is a small version of the JS I have ('agree' is the radio button):
$('myForm').submit(function(e){
var firstName = $('first-name').val();
var pattern = /^$/;
var error = '';
var checkbox = document.getElementById('agree');
if(pattern.test(firstName)){
error += 'Error: enter first name.\n';
}
if(error.length != 0){
alert(error);
e.preventDefault();
}
});
I want to hide the radio button until the first name part of the form is filled out then the radio button will appear.
Put an id in your radio like this :
<input type="radio" id="rad" />
Then hide it like this using jquery :
$('#rad').hide();
Then an example of how you can make it show when something happens would go a bit like this :
If ($('#something') > 10) {
$('#rad').show();
}
Hope this helped :)
I would use plain JavaScript for this:
<input type="text" name="first-name" value="" onchange="document.getElementById('agree').style.display = (this.value == '' ? 'block' : 'none' );"/>
<input type="checkbox" name="agree" value="Agree" style="display:none"/>
Edit:
Other ways to do this is to use onkeydown, onkeyup or onblur instead of onchange
Here is a simple example using jquery... http://jsfiddle.net/wa8rxj43/2/
HTML
<input type="text" id="name" class="name">
<input class="not-display" id="somecheck" type="checkbox" name="vehicle" value="Car" checked>
JavaScript
$('#somecheck').hide();
$("#name").bind({
'input':function(){
if(this.value.length > 0)
{
$('#somecheck').show();
}
else
{
$('#somecheck').hide();
}
}
});
Edit: Removed CSS per OP's request.

javascript confirm when checking a checkbox by clicking on the label

I have a checkbox on a form that does something dangerous. So, I want to make sure the user is really sure when they check this item, but I don't want to warn them if they're unchecking the checkbox.
My issue is this works fine if they click on the actual checkbox to uncheck it, but not the text of the label.
http://jsfiddle.net/j2ppzpdk/
function askApply() {
if (document.getElementById("apply").checked) {
var answer = confirm("Are you sure about that?");
if (!answer) {
document.getElementById("apply").checked = false;
}
}
}
<form>
<label onclick="askApply();">
<input type="checkbox" name="apply" id="apply" value="1" /> Apply
</label>
</form>
Some notes:
Better add the event listener to the element that changes (the checkbox), not its label.
Better listen to change event instead of click. For example, the checkbox could be changed using the keyboard.
Better avoid inline event listeners. You can use addEventListener instead.
document.getElementById('apply').addEventListener('change', function() {
if(this.checked) {
var answer = confirm("Are you sure about that?");
if (!answer) {
document.getElementById("apply").checked = false;
}
}
});
<form>
<label>
<input type="checkbox" name="apply" id="apply" value="1" />
Apply
</label>
</form>

toggle checkbox values

I am trying to toggle the value of a checkbox using the following code:
<div class="control-group">
<label class="control-label checkbox" for="IsViewAsWebpage">
{{#if this.IsViewAsWebpage}}
<input type="hidden" id="IsViewAsWebpage" name="IsViewAsWebpage" value="true"/>
<input type="checkbox" class="enable-checkbox" checked />
{{else}}
<input type="hidden" id="IsViewAsWebpage" name="IsViewAsWebpage" value="false"/>
<input type="checkbox" class="enable-checkbox" />
{{/if}}
<span>View as Webpage</span>
</label>
</div>
'click .enable-checkbox': function (e) {
if (e.currentTarget.parentElement.htmlFor == "IsViewAsWebpage") {
this.$('#IsViewAsWebpage').is(':checked');
}
}
I know I am misssing something in the click function. I would basically want to toggle the checkbox value when the user clicks on it. Can someone point me to the right directions pls. Thank you.
When your checkbox gets clicked, it's going to toggle. That's the way checkboxes work.
If you want the hidden input to change value when the checkbox is toggled, I think what you want is this:
$(".enable-checkbox").change(function (e) {
if($(this).parent().attr("for") == "IsViewAsWebpage") {
var checked = $(this).is(":checked"); // Returns true/false.
$('#IsViewAsWebpage').attr("value", checked); // Sets true/false.
}
});
If you want to use handlebars.js to switch content when you click an check box, you will need to replace your content by calling handlebars each time you make a modification to your checkbox
$(".enable-checkbox").change(function (e) {
if($(this).parent().attr("for") == "IsViewAsWebpage") {
var checked = $(this).is(":checked");
IsViewAsWebpage = checked;
$("#yourcontainer").html(Handlebars.compile(yourtemplatesource));
}
}
then your IsViewAsWebpage variable should be global and your mustache condition should only be :
{{#if IsViewAsWebpage}}
But this is complicated for nothing... just use Aesthete solution, it will save you a lot of time.

Categories