JavaScript can be used to enable or disable a text box within a GridView when a checkbox is changed

I have a GridView on a webpage containing a Textbox and a CheckBox. I want the Textbox to be enabled when the CheckBox is checked, and disabled when it is unchecked using pure javascript.

Can anyone help me solve this issue? Thank you in advance.

<asp:GridView ID="grdBasicApproval" runat="server" AutoGenerateColumns="false" Width="90%"
                    CssClass="mGrid" DataKeyNames="EmpId">
                    <Columns>
                        <asp:TemplateField Visible="true" HeaderText="Remark">
                            <ItemTemplate>
                                <asp:TextBox ID="txtRemark" runat="server" Width="125px" TextMode="MultiLine" Style="resize: none"></asp:TextBox>
                            </ItemTemplate>
                            <ItemStyle HorizontalAlign="Center" />
                        </asp:TemplateField>
                        <asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="7%">
                            <HeaderTemplate>
                                <asp:CheckBox ID="chkHeader" runat="server" Text="All" onclick="CheckAll(this);"
                                    TextAlign="Left" />
                            </HeaderTemplate>
                            <ItemTemplate>
                                <asp:CheckBox ID="chkChild" runat="server" onclick="return Check_Click(this);" />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>

Here is my JavaScript code:

$(document).ready(function () {
        try {
            $("input[type=checkbox][id*=chkChild]").click(function () {
                if (this.checked) {
                    alert("Checked");
                    $(this).closest("tr", "").find("input[type=TextBox][id*=txtRemark]").attr("disabled", true);
                }
                else {
                    alert("UnChecked");
                    $(this).closest("tr", "").find("input[type=TextBox][id*=txtRemark]").attr("disabled", true);

                }
            });
        } catch (e) {
            alert(e);
        }
    });

Answer №1

To add functionality to a checkbox within a GridView, you can utilize the RowDataBound event handler in code-behind to pass the textbox value to a JavaScript function that will enable or disable the textbox based on the checkbox state.

Code behind

void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{    
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chkBox = (CheckBox)e.Row.FindControl("checkBoxId");
        TextBox textBox = (TextBox )e.Row.FindControl("textBoxId");
        chkBox.Attribute.Add("onclick", "EnableDisable(this, '" + textBox.ClientID + "');" );
    }    
}

Javascript

function EnableDisable(chkbox, textBoxId)
{
   document.getElementById(textBoxId).disabled = !chkbox.checked;  
}

Answer №2

Here is a snippet of code that allows you to toggle the enabling and disabling of a textbox based on whether a checkbox is checked:

<asp:TextBox runat="server" ID="txt_Text1"></asp:TextBox>
<asp:CheckBox runat="server" ID="chk_Check" onclick="ToggleTextbox();" />
 <script>
    function ToggleTextbox() {
        var checkbox = document.getElementById('<%= chk_Check.ClientID %>');
        if(checkbox.checked)
           document.getElementById('<%= txt_Text1.ClientID %>').disabled = true;
        else
           document.getElementById('<%= txt_Text1.ClientID %>').disabled = false;
    }
 </script>

Answer №3

Test Out

CSS

   <input type="checkbox" id="check1" />

Python

$(document).ready(function() {
     $("input[type=checkbox][id*=check1]").change(function() {
       if ($(this).is(":checked")) {
         $(this).siblings("input[type=text]").prop("disabled", false);
       } else {
         $(this).siblings("input[type=text]").prop("disabled", true);
       }
     });
});

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

Error: An unexpected identifier was not caught in the jQuery Ajax function

My code seems correct, but I'm getting an error that says "undefined identifier." I'm new to javascript and would appreciate any help or advice you can offer. Thank you in advance! $('#media-select').on('change',function(){ ...

The Django Rest Framework appears to be lacking the functionality to allow image uploads, despite the presence of an ImageField in the model

Having trouble with Django Rest Framework as it doesn't display the option to upload images. I have an imageField in my models but when I try to create a new item by visiting the API URL, I receive a GET http://127.0.0.1:8000/api/person-create/ 405 (M ...

What is the reason for HereMap factoring in stopOver time when calculating travel time for the destination waypoint?

I am currently working on a request using the HereMap Calculate Route API. Waypoint 0 does not have any stopOver time, but waypoints 1 and 2 do have stopOver times. Below is an example of the request: https://route.ls.hereapi.com/routing/7.2/calculateroute ...

Adjust the formatDate function in the Material UI datepicker

I recently implemented the material-ui datepicker component with redux form and it's been working great. However, I have encountered a minor issue. Whenever I change the date, it displays in the input field as yyyy-mm-dd format. I would like it to app ...

What is the most effective way to prevent duplicate entries from being added to the database?

I am facing an issue with my forum application built using asp.net, c#, sql server, and linq to sql. The problem arises due to multiple data inserts triggered by either pressing the insert button, refreshing the browser, or clicking back. What is the most ...

Clicking on Only One Card in Material UI React

I've encountered an issue with my code: const useStyles = makeStyles({ card: { maxWidth: 345, }, media: { height: 140, }, }); export default function AlbumCard(props) { const classes = useStyles(); let ...

Creating an HTTP interceptor in Backbone: A step-by-step guide

After gaining experience with backbone, I decided to delve into learning angular. The features of angular really caught my interest, especially the HTTP interceptor. I began thinking about how to implement this functionality in backbone to display a spin ...

Need a hand with ajax?

Recently, I've been having issues with a PHP script that packages files into a zip based on user input. Unfortunately, the server occasionally errors out and causes all the form data to be lost. To prevent this from happening in the future, I was info ...

Unconventional tendencies of Select component in Vue.js

I have a basic Vue component with two separate sections. In each section, users can make selections from dropdown menus that update the variables value1 and value2. The issue arises when transitioning from "stepOne" to "stepTwo", as unexpectedly the value ...

Adjust the image size to match the height of its parent element and ensure it stays resized when the window is

Looking for some assistance with my code. Here's an example of what I'm working on - http://jsfiddle.net/urK7t/ You can also view the full-size page here - In terms of the concept: I am trying to create a DIV element that has 100% width and h ...

Tips for effectively managing errors in JavaScript programming

Whenever I need to throw an error using JavaScript, this is what I do: throw new Error() It works perfectly fine. However, if I try to pass a number like this: throw new Error(500) The output becomes: Error: 500 In this case, 'Error: &apos ...

Attempting to utilize solution for the "ajax-tutorial-for-post-and-get" tutorial

I've been exploring the implementation of the second answer provided in a post about Ajax tutorials on a popular coding forum. Despite following the instructions, I encountered an issue where the $.ajax script, triggered by an "onclick" function, only ...

What is the definition of this ""!sequence"?

As part of my current project, I am diving into an outdated code library within my organization to document it and repurpose it for future projects. Surprisingly, there is absolutely no documentation in the Library, not even comments, but I am determined t ...

Troubleshooting checkbox problem with AJAX request in PHP

Experiencing an issue with a simple AJAX call that checks if a checkbox is checked. Currently, regardless of whether the checkbox is checked or not, it always prints "not checked". I've attempted changing the "POST"/"GET" methods in the PHP code, howe ...

The onClick event handler fails to trigger in React

Original Source: https://gist.github.com/Schachte/a95efbf7be0c4524d1e9ac2d7e12161c An onClick event is attached to a button. It used to work with an old modal but now, with a new modal, it does not trigger. The problematic line seems to be: <button cla ...

The Bootstrap Modal containing a JQuery Validation Form refuses to submit even after successful validation

UPDATE: To provide some context for the question, I have created another Fiddle that showcases the same form outside of the modal. Under the right conditions, such as entering an email address and clicking the Get Started button, the form submits correct ...

Converting a 'div' element into a dropdown menu with CSS and Jquery

I am facing a challenge where I have a collection of buttons enclosed in a div that I want to resemble a dropdown: <div id = "group"> <label> Group: </ label> <div value =" 1hour "> 1h < / div> <div value =" 2hou ...

Using an array as the source for your Mui Autocomplete instead of JSON

I'm attempting to recreate the autocomplete MUI example shown here, but with a slight variation. Instead of utilizing a JSON data structure, I am simply passing an Array. Here is what I have tried: export default function SearchTutorialArray() { con ...

Improving the Sum of Pairs solution on Codewars

Seeking assistance in optimizing a solution for a problem that has already been identified. However, the existing code is not efficient when dealing with large arrays - view the problem on codeWars : Sum of Pairs Below is the current code snippet: var s ...

Can you explain the compatibility between comet and PHP?

As I utilize Comet iframe, I simply send script tags from the backend PHP file to the frontend where JavaScript displays them. I would appreciate it if someone could provide a concise explanation of how the comet server fits into the equation and how comm ...