Enable the EditorFor if the checkbox is checked

I need help creating a JavaScript function that will disable certain form elements (EditorsFor) when a checkbox is unchecked and enable them when it is checked. I have tried various codes from the internet but none seem to work.

Here is a snippet of my View code:

@{Html.RenderPartial("_PartialError");}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

(...)

    <div class="form-group">
        @Html.LabelFor(model => model.Czy_zuzywalny, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="checkbox">
                @Html.EditorFor(model => model.Czy_zuzywalny)
                @Html.ValidationMessageFor(model => model.Czy_zuzywalny, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>

    (...)
}

I have attempted to write a JavaScript function in a separate file, but it doesn't seem to be working as expected:

$(document).ready(function ()
{
    $("#Czy_zuzywalny").click(function ()
    {
        if ($("#Ilosc_minimalna").attr("disabled") == "")
        {
            $("#Ilosc_minimalna").attr("disabled", "disabled");
            $("#Ilosc_optymalna").attr("disabled", "disabled");
            $("#Ilosc_minimalna").attr("value", "0");
            $("#Ilosc_optymalna").attr("value", "0");
        }
        else
        {
            $("#Ilosc_minimalna").attr("disabled", "");
            $("#Ilosc_optymalna").attr("disabled", "");
        }
    });
});

Unfortunately, the code does not work as intended. Can anyone offer guidance on how to solve this issue?

Answer №1

Make sure to update your jQuery code as follows:

$(document).ready(function () {
    $("#Czy_zuzywalny").click(function () {

        if ($("#Ilosc_minimalna").is('[disabled=disabled]')) {
            $("#Ilosc_minimalna").removeAttr("disabled");
            $("#Ilosc_optymalna").removeAttr("disabled");
        }
        else {
            $("#Ilosc_minimalna").attr("disabled", "disabled");
            $("#Ilosc_optymalna").attr("disabled", "disabled");
            $("#Ilosc_minimalna").attr("value", "0");
            $("#Ilosc_optymalna").attr("value", "0");                
        }            
    });
});

Your current if condition may not work as expected because the 'disabled' attribute doesn't have a value when an input is enabled. It's better to use removeAttr("disabled").

UPDATE: See this working JSFiddle demo

UPDATE 2:

To include this script in the Create view and ensure it appears after the jQuery script tag in the rendered HTML, follow these steps:

Insert a call to RenderSection in your Layout file just before the closing </body> tag like so:

@RenderSection("scripts", required: false)

This will allow you to include a 'scripts' section in your views, with its contents replacing the RenderSection call in the final HTML. Remember that the required: false parameter indicates that this section is optional.

Then, in your Create view, add the following outside of any section:

@section scripts {
<script src="/scripts/CheckBoxItemCreate.js"></script>
}

I hope this explanation helps!

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

Auto-fit HTML Webpage Resizer Simplified

Just finished my very first jQuery project, a simple full-width slider. I've been focusing on HTML & CSS and currently working with C#. The problem is that I don't want the page to be scrollable; I want it to autofit to the webpage. Imagine ope ...

Some browsers are experiencing issues with Javascript functionality

My JavaScript code is functioning perfectly on my development machine in Chrome, Firefox, and Safari. However, when others test it on their browsers, the value update does not work at all. Can anyone suggest how I can replicate this issue locally? Browser ...

Contrasting Debug and Release Configurations in the .NET Framework

In reference to my earlier inquiry about double and floats in C, I am now curious about whether there exists a detailed resource outlining the variances between debug and release modes in a C# web application. Could someone shed light on the disparities t ...

Using ReactJS to Retrieve Input Value from Prompt Box and Save to Database

I'm currently developing a MERN application and I need to allow users to edit the food name by clicking on the prompt box that pops up when they click the Edit button. The approach I was following can be found in this link: [https://stackoverflow.com ...

The disadvantages of manipulating DOM in controllers in AngularJS

Many experts advise against performing DOM manipulations in AngularJS Controllers, but it can be challenging to fully understand why this is considered a best practice. While sources mention issues with testing and the primary purpose of controllers for di ...

JavaScript click event to open a URL in a new window

I am trying to create a hyperlink with text using HTML, and I want it so that when the user clicks on it, it redirects to a specific URL. I am new to JavaScript! Here is my code: <a class="dt-button add_new_table_entry DTTT_button DTTT_button_new" tab ...

Adjust the contents of a DIV depending on which Toggle button is selected

When a user clicks on either "Twin Bed" or "King Bed", the content inside the "demand-message" should change to either "high demand" or "Only ??? rooms left". The ID will remain the same for both buttons due to existing logic. However, the message display ...

Step-by-step guide on running two JavaScript codes sequentially to ensure accurate results

I am currently working on an MVC project where I need to display the user's current location city in the top right corner of a webpage. The first javascript code fetches the city name, and the second one retrieves the weather conditions of that city. ...

What is the best way to access ASP.NET intrinsic objects in C# web service code?

My main objective is to validate the incoming X.509 security certificate against a database in order to grant access to my web service. To achieve this, I need to retrieve the certificate sent by the client. Although I believe I can accomplish this task by ...

What are some ways to personalize column design when a Kendo grid column is automatically created?

I am populating the Kendo grid with data using JavaScript: var dataSource = new kendo.data.DataSource({ transport: { read: { url: "@Url.Action("GetProductList", "Home")", type: "POST&qu ...

Creating a dynamic menu in antdesign requires a few simple steps to customize the

I am looking to implement a dynamic menu using antdesign version 4.19.5 Below is the code for a static menu: <Menu selectable selectedKeys={activeKey}> { <Menu.SubMenu title="Main Title 1" > <Menu.Item key={&a ...

Utilize vue.js to save the components of an object

data() { return: { user: {}, userName: "", userAge: "" } }, methods: { saveUserName: function() { this.userName = this.newUserName; this.$refs.userNameModal.hideModal(); this.$ ...

Modify the color of chips when the checkbox is toggled in Materialize CSS

I have been scouring the internet for a solution to my issue. Currently, I am working with materialize css chips and I am trying to achieve a specific functionality. I want the color of the last chip to turn green and the rest to turn red when a checkbox ...

Controller function failing to trigger

I'm new to asking questions, so if I've made a mistake, please let me know. I've searched for an answer here but couldn't find one. Any help would be greatly appreciated. I'm attempting to load a list of "Countries" using a contro ...

Acquiring a list of documents from a nested list in a collection using their respective ids

I have a collection of documents structured like this: [ // 1 { "_id": ObjectId("573f3944a75c951d4d6aa65e"), "Source": "IGN", "Family": [ { "Countries": [ ...

Using Three.js WebGL to create a custom circle with unique fill and border colors generated from a shader

Currently, I am utilizing Three.js alongside the WebGLRenderer. I am exploring ways or searching for an example on how to create circles using CircleGeometry and have the ability to manipulate their fill and border color through a vertex or fragment shad ...

Exploring Vue.JS with Staggered Transitions and Enhancing User Experience with Loading More

The VueJS Guide offers a clever method for using the item's index to create a delayed transition for the items in the data set. You can learn more about it here. While this approach works great when the data set remains static, I'm encountering a ...

Utilizing Vue.js for Keyboard Binding

I'm brand new to coding and Vue, and I've hit a roadblock in my project. I'm creating a JavaScript calculator that needs to be usable both with a mouse and keyboard. While I've managed to make it work with the mouse, I just can't ...

Issue: Unable to link to 'options' as it is not recognized as a valid attribute of 'chart'

Here is a sample component code snippet: import { Component, OnInit, Input } from '@angular/core'; import { Observable } from 'rxjs/Rx'; @Component({ selector: 'chart', templateUrl: 'app/comps/chart.html', ...

Generating a new date instance using a specified date string and locale settings

After scouring SO and coming up empty, I'm forging ahead with my question: I've got a date string that's dependent on locale, along with the locale info itself. For example, dateStr = '06/07/2021' and locale='en-GB'. H ...