My AJAX checkbox change event is not functioning, what could be causing this issue?

This is a sample of the code I'm working with:

<form asp-action="Save" asp-controller="ClassesHeld" method="post">
        <input asp-for="ClassHeldId" value="@Model.ClassHeldId" hidden />
        <div class="form-group">
            <label>Student</label>
            <input asp-for="@Model.Student" value="@Model.Student" class="form-control" readonly />
        </div>

        <div class="form-group">
            <label>Grade</label>
            <input id="Grade"asp-for="Grade" type="number" value="@Model.Grade" class="form-control" min="0" max="5" />
        </div>

        <div class="form-group">
            <label>Attendance</label>
            <input id="Attendance" class="form-check-input" asp-for="Attendance" type="checkbox"/>
        </div>

        <button class="btn btn-primary" type="submit" value="Save">Save</button>
    </form>

    <script>
        $("#Attendance").on("change", function () {
            $("#Grade").attr("disabled", this.checked);
        });
    </script>

Despite trying multiple different solutions, clicking on the checkbox does not trigger any desired action. Even resorting to a simpler solution like the following did not yield results:

document.getElementById('Attendance').onchange = function () {
    document.getElementById('Grade').disabled = this.checked;
}; 

I have exhausted various resources and tried different scripts, but none seem to work. I must be overlooking something obvious, but even after spending considerable time, I am unable to identify the issue.

My apologies if this question seems trivial or novice-like. I am hoping for some guidance in resolving this issue.

UPDATE: To provide additional context, the form successfully saves data to the database upon submission. The only area where it falls short is in disabling the ability to edit the "Grade" field when the student has not attended.

The primary goal remains to disable the input field when the "attendance" checkbox is checked.

Answer №1

The .attr() method is limited to managing strings; Therefore, when you need to change an attribute such as disabled or checked using a boolean or another type of value, it's recommended to use the prop method.

For more details, you can refer to this post: .prop() vs .attr()

You can run the code snippet provided below.

 $("#Attendance").on("change", function () {
        $("#Grade").prop("disabled", this.checked)
       
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form asp-action="Save" asp-controller="ClassesHeld" method="post">
    <input asp-for="ClassHeldId" value="@Model.ClassHeldId" hidden />
    <div class="form-group">
        <label>Student</label>
        <input asp-for="@Model.Student" value="@Model.Student" class="form-control" readonly />
    </div>

    <div class="form-group">
        <label>Grade</label>
        <input id="Grade"asp-for="Grade" type="number" value="@Model.Grade" class="form-control" min="0" max="5" />
    </div>

    <div class="form-group">
        <label>Attendance</label>
        <input id="Attendance" class="form-check-input" asp-for="Attendance" type="checkbox"/>
    </div>

    <button class="btn btn-primary" type="submit" value="Save">Save</button>
</form>

<script>
   
</script>

Answer №2

To solve this issue, consider removing the disabled attribute only when it is not required. You can achieve this with the following code snippet:

$(document).ready(function() {
    $("#Attendance").on("change", function () {
        if (this.checked) {
               $("#Grade").attr("disabled", true);
        } else {
               $("#Grade").removeAttr("disabled");
        }
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show session in HTML using ng-click after reloading the page

I am currently using the express-session package to store product prices in my application. Everything seems to be functioning correctly, however I am encountering an issue when trying to display the session data in HTML. For example, if there are 2 produc ...

When the beforeSend function of jQuery AJAX returns false, it triggers the $.ajaxError event

function load() { var url = buildUrl(null, true); $.ajax(url, { cache: true, dataType: 'json', beforeSend: function(xhr) { if (typeof plugin.cache[url] != ...

When the Angular UI Bootstrap typeahead ng-model is cleared, it displays as null

The filter is performing admirably, however, after deleting the entered text, the {{filterlist.name}} displays null. This leads to the tables appearing empty due to the presence of null. Check out the demo here: https://plnkr.co/edit/1QVdctw1hr4ggJOtFHUZ? ...

Issue with triggering a modal while simultaneously closing another one

Let's consider this situation. I currently have a modal called Modal A, which has 2 buttons in the footer: Save and Close. When I click on the "Save" button, my intention is to close Modal A and open Modal B. The code that achieves this functionality ...

Obtaining DOM data following an AJAX request

I am looking to retrieve DOM values from Perl without having to manually use a browser and debugger. These DOM values are populated after an AJAX call, and a sample function for one of these values may look like this: <script language="javascript"> ...

Why does using rgba color with an alpha value cause my div to become see-through?

I am currently attempting to assign a background color to a specific style of pop-up, but whenever I use a value that includes an alpha channel, it ends up being transparent. This is the CSS code I have been using: --color: 255, 144, 106, 0.18; background ...

Using PHP and Ajax to create dynamically linked dropdown menus

I am struggling with my code and need assistance. I would like to retrieve values from the database based on the selection made in the first combo box. The first combo box contains subject IDs, which I intend to use in my SQL query to determine the values ...

Tips on expanding the dimensions and incorporating more members in a radar graph's Chartjs tag

I need to make some adjustments to the font size and color in a radar chart. Specifically, I want to change the name on the side of each data point. I have already tried adjusting the legend labels using the following code: options={{ ...

What are the consequences of altering meta tags once the DOM has fully loaded?

While delving into the A-Frame source code, I noticed that the library uses JavaScript to set various meta tags. It seems safe in the context of A-Frame as Mozilla recommends importing their library as a blocking, synchronously loaded script in the <he ...

Enhance the numerical value displayed in jQuery UI tooltips

I have folders with tooltips displaying text like '0 entries' or '5 entries' and so on. I am looking for a way to dynamically update this tooltip number every time an item is added to the folder. The initial count may not always start a ...

Do you need to define a schema before querying data with Mongoose?

Is it necessary to adhere to a model with a schema before running any query? And how can one query a database collection without the schema, when referred by the collection name? This scenario is demonstrated in an example query from the Mongoose document ...

Experiencing duplicate execution of $onChanges in AngularJS version 1.6

I might be overthinking this, but that's why I'm seeking help. :) Note: In the example below, the controller alias for the component is "ctrl". var ctrl = this; Imagine we have a component with two bindings, one of which is optional: bindings: ...

What is the best way to add a numbered alert to a button using HTML5, jQuery, PHP, or JavaScript?

I have a button on my HTML page that directs users to a page containing email features. I'm looking for a way to show users the number of unread messages they have before they click on the button to view them. I want this to be a subtle alert without ...

Attempting to iterate over an array of objects is resulting in a TypeError: null is not an object when evaluating 'daysData.map'

Hi everyone, I hope you're all well. I've been searching for a specific solution to an issue I'm facing in ReactJS. I'm trying to map over an array that I fetch from my local system, but I keep encountering this error in the console: Ty ...

Dropdown selection triggers an Ajax request

I have encountered an issue while attempting to make an Ajax request to the page chosen in a drop-down menu. While most of my script code works fine in binding a mouse click to table rows, it seems to fail in this particular scenario. The error message I r ...

Steps for creating a TypeScript project for exporting purposes

Forgive me for my lack of experience in the js ecosystem. Transitioning from static languages to typescript has been a positive change, though I still find myself struggling to grasp the packaging/module system, especially when coupled with typescript defi ...

What is the best way to bring a JavaScript library into a TypeScript project if the library includes a declaration file?

I have been attempting to utilize the type definitions from the callbag library. Unlike other libraries, callbag declares its type definition file within its package.json and is not included in DefinitelyTyped. However, when I try to import the library, I ...

I am facing an issue with file manipulation within a loop

I need to set up a folder with different files each time the script runs. The script should not run if the folder already exists. When I run the script, an asynchronous function is called and one part of this function causes an issue... This is my code : ...

How to Retrieve JSON Response in Link Function within AngularJS Directive

I have decided to implement a chart library called Plotly in my project. To ensure reusability, I am creating a directive in AngularJS that will allow me to easily integrate the library in the future. The directive will receive an object as input to creat ...

Generate an inclusive list featuring li elements with intricately detailed content within each

Currently, I am in the process of developing a web component and here is my code snippet: <ul class="list-with-arrow${this.inverse ? '--inverse' : ''}"> ${this.listData.map((item, index) => { ...