1

I'm trying to see if I can disable a checkbox on a form on two certain days of the week, say if I want the checkbox disabled on Monday and Friday. I have the code written to return a day value as a number, then convert it to a day(name). The code I have been altering was disabling all input checkboxes onLoad that have a certain class applied to them, so I've been altering that to see if I can write an If/Else statement, but can't seem to get it right. Any ideas what I can change this to, so it will work?

var d = new Date();
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.getElementById("demo").innerHTML = days[d.getDay()];

if days = 'Monday' {
    $('.sum').attr('disabled', true);
} else {
    $('.sum').attr('disabled', false);
}

<p style="margin: 20px;">Today is <span id="demo"></span>!</p>
<input style="margin: 20px 0 20px 20px;" value="50" type="checkbox" class="sum" data-toggle="checkbox" name="item"> Item 1 (Not availalbe Mondays/Fridays)

Thanks in advance for any insight!!

1

2 Answers 2

2
<script>
window.onload = function () { 
    var d = new Date();
    var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
    document.getElementById("demo").innerHTML = days[d.getDay()];
    // if (days== 'Monday') {
    if (days[d.getDay()]== 'Tuesday') {
        document.querySelectorAll(".sum").forEach(function(actual) {
            actual.disabled=true;
        });
    }   
}
</script>

<p style="margin: 20px;">Today is <span id="demo"></span>!</p>
<input style="margin: 20px 0 20px 20px;" value="50" type="checkbox" class="sum" data-toggle="checkbox" name="item"> Item 1 (Not availalbe Mondays/Fridays)
  1. If you want to put the script on top, use the onload method to ensure the wole DOM is loaded, else the script must go at the bottom of the html
  2. I changed Monday to Tuesday in code to test it today. (see comment code)

Have a good day!

Sign up to request clarification or add additional context in comments.

Comments

0

You've got a few issues here:

  • Your if statement needs parentheses () around the condition
  • Your condition should use == or (better) === for comparison, not = which does an assignment
  • Comparing days to 'Monday' will always fail because days is an array.
  • $('.sum').attr('disabled', true) isn't a good way to disable the element - use $('.sum').prop('disabled', true) instead

So I'd try using the following code:

if ( days[d.getDay()] === 'Monday' ) {
    $('.sum').prop('disabled', true);
} else {
    $('.sum').prop('disabled', false);
}

...or, more concisely

const isDisabled = ( days[d.getDay()] === 'Monday' ); //true or false
$('.sum').prop('disabled', isDisabled );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.