Activate and deactivate text field when checkbox is selected in a table

So here's the scenario: I have a table that is already filled with data, and I want to add checkboxes and textboxes into it. Check out the code snippet below:

int count1 = 0;
        TableCell tc;
        foreach (TableRow tr in Resource_TBL.Rows)
        {
            tr.Cells.Add(tc = new TableCell());
            CheckBox cbox = new CheckBox();
            cbox.ID = ""+count1;
            cbox.Attributes.Add("onclick", "document.getElementById('textbox_" + count1 + "').disabled=this.checked;");
            tc.Controls.Add(cbox);

            tr.Cells.Add(tc = new TableCell());
            TextBox tbox = new TextBox();
            tbox.ID = "textbox_" + count1;
            tbox.CssClass = "form-control";
            tbox.Enabled = false;
            tbox.Attributes.Add("placeholder", "Enter Detail Here");
            count1 += 1;
            tc.Controls.Add(tbox);
        }

I attempted this as well:

cbox.Attributes.Add("onclick", "document.getElementById('textbox_" + count1 + "').Enabled=this.checked;");

Unfortunately, it didn't work and threw an error stating (Unable to set property 'Enabled' of undefined or null reference).

Does anyone know of another approach to achieve this functionality?

Answer №1

The textbox doesn't have an "Enabled" property probably due to its naming convention being in Pascal-case.

cbox.Attributes.Add("onclick", "document.getElementById('textbox_" + count1 + "').disabled = !this.checked;");

Answer №2

It appears that your ID is incorrect. I recommend utilizing jQuery as it offers a more concise and readable syntax.

Answer №3

int counter = 0;
        TableCell tableCell;
        foreach (TableRow row in Resource_TBL.Rows)
        {
            CheckBox checkbox = new CheckBox();
            checkbox.ID = ""+counter;
            TextBox textbox = new TextBox();
            textbox.ID = "textbox_" + counter;
            textbox.CssClass = "form-control";
            textbox.Enabled = false;
            textbox.Attributes.Add("placeholder", "Enter Detail Here");
            counter += 1;
            checkbox.Attributes.Add("onclick", "document.getElementById('" + textbox.ClientID + "').disabled=!this.checked;");
            row.Cells.Add(tableCell = new TableCell());
            tableCell.Controls.Add(checkbox);
            row.Cells.Add(tableCell = new TableCell());
            tableCell.Controls.Add(textbox);
        }

Remember to avoid manually assigning IDs, as they can change dynamically when using masterpages or other controls. Utilize ClientID to accurately identify the control's ID on the page.

It is advisable to create controls first and then add them to the table hierarchy later on. Furthermore, consider adding a "!" before this.checked to prevent the textbox from being disabled immediately upon checkbox selection.

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

Submitting an mvc partial view form to send data from the parent view

I am currently working on a MVC 5 App where I have a Parent View that includes a Partial View, allowing users to load images. Upon submitting, the Parent view calls a .Ajax function defined within it, which in turn calls a Method/Controller. My requireme ...

Strategies for reloading the previous ViewState when navigating back to a previous page

My goal is to reload all the user changes when they want to go back to a previous page. I attempted to utilize the LoadViewState() and SaveViewState() methods in the following way: protected void Page_Load(object sender, EventArgs e) { ...

Mastering Vuex: effectively managing intricate data structures and dynamic state transformations

Let's say I'm utilizing an external API that interacts with Machine objects. With the API, you can create a Machine using createMachine, resulting in a complex object with various nested properties and functions to modify its state. The API inclu ...

Utilizing Axios Response Data in Vue JS to Enhance User Experience

Recently delved into Vue and not exactly a fan of Javascript, so I've set up a Vue component that uses Axios to fetch some data. However, I'm struggling to display this data in my form elements. I have Axios intercepting the response and retriev ...

Prevent errors arising from PropertyGrid usage

Utilizing a PropertyGrid control in my code, I have successfully retrieved all properties and their corresponding values. However, when attempting to change a property to an invalid value (such as "123456789008765" for an integer field), an error is throw ...

The contact form fails to send even after passing the validation process

I am currently working on a contact form backend using node.js and nodemailer for sending messages. However, I'm encountering an issue where even after correctly filling out the inputs, it still displays an error message stating that the inputs are in ...

Retrieving row and column values from an 81-element indexed array

I am working with an indexed JavaScript array that contains exactly 81 elements. These elements will form a 9x9 grid, similar to a Sudoku puzzle. Right now, I am trying to figure out the most efficient way to extract row and column values from this array. ...

Delete the current code within the specified div element

Objective: The goal is to ensure that any HTML syntax code or data inside the specified <div id="feedEntries"></div> element is removed, leaving it empty. Issue: What specific syntax is required to remove all content within <div id="fe ...

The efficiency of Ajax JSON timeouts needs improvement

Currently, I'm in the process of developing an interactive map with specific functionalities. Essentially, the user will click on a year (stored as var currentyear) and then select a country (its name stored as var thenameonly). Subsequently, an AJAX ...

.NET Compact Framework - Utilizing Cookies for Web Service Connectivity

Trying to access a Web Service from my .NET Compact Framework 3.5 application, but running into an issue with authentication using cookies. The problem is that the Web Service requires cookies for authentication, and in my desktop application I normally us ...

What steps can I take to enable search functionality in Ckeditor's richcombo similar to the regular search feature in

I am currently developing a custom dropdown menu using the rich combo feature in CKEDITOR. One of my goals is to include a search functionality within the dropdown, such as a key press search or an input textbox search. This is how my dropdown box appear ...

Showing outcomes by making rapid consecutive AJAX requests

If you need a visual representation, I have a PHP script for a Hotel Management application that showcases a calendar (with columns representing days of the month and rows displaying prices per day). This script can be accessed in edit mode, where it gene ...

JQuery functionality is disrupted by the update panel on the master page

I'm facing an issue with three anchors on the page - one for time in, one for time out, and one for the menu. Initially, everything works fine when the page loads for the first time. However, clicking on the time in or time out button causes the menu ...

Encountering a challenge in Angular 8: Unable to locate a supporting object matching '[object Object]'

I am having an issue trying to retrieve the Spotify API from the current user's playlists. While I can see it in my console, when I attempt to insert it into HTML, I encounter the following error: ERROR Error: Cannot find a differ supporting object ...

Ways to Achieve the Following with JavaScript, Cascading Style Sheets, and Hypertext

Can someone help me convert this image into HTML/CSS code? I'm completely lost on how to do this and don't even know where to start searching for answers. Any assistance would be greatly appreciated. Thank you in advance. ...

Local variable reference getting lost in a loop during a jQuery Ajax call

Currently, I am facing an issue with my jQuery ajax calls within a loop. The problem arises when each ajax call returns and I need to retrieve a specific value associated with the original call. However, due to further iterations in the loop, the value of ...

Stopping setTimeout when leaving the current page: Is it possible?

Good evening, I am looking for advice on how to cancel a setTimeout function when a user navigates to other pages (for example, by clicking other links or pressing the back button in the browser, but not by changing tabs). I have attempted to use the windo ...

Exploring the integration of JSONP with the unmatched features of Google

I am attempting to utilize the Google maps directions API by using jquery $.ajax. After checking my developer tools, it seems that the XHR request has been completed. However, I believe there may be an issue with the way jquery Ajax handles JSON.parse. Y ...

Using jQuery and Flask-WTF to achieve live word count in a TextAreaField - a step-by-step guide!

I am interested in adding a real-time word count feature to a TextAreaField using jQuery. I found an example that I plan to use as the basis for my code: <html lang="en"> <head> <script src= "https://code.jquery.com/jquery ...

Using asynchronous LINQ to filter ElementHandle[] in PuppeteerSharp

Recently, I decided to transition my Selenium Application to Puppeteer Sharp in order to gain a better understanding of this framework. The challenge arises as my application operates on a site for which I do not have access to modify the source code, thus ...