Selecting classes using JQuery on a pair of input elements and a pair of buttons

Currently, I am utilizing JQuery with two input text elements (set as readonly) and two buttons. The goal is for only input 1 to become read/write when button 1 is clicked, and for only input 2 to become read/write when button 2 is clicked. If the corresponding button is clicked again, the corresponding input should revert back to being readonly. However, my current script changes the readonly attribute of both inputs regardless of which button is clicked. According to some user suggestions on Stack Overflow, only one event should be fired for each specific input element.

Please Note: Although using an id instead of a class selector can be a solution, in my case the input and button tags are generated dynamically through a loop using data from a database. Therefore, the number of elements created each time is unknown. Following the feedback provided by the user mentioned earlier, we need to figure out how to achieve this functionality within such a dynamic scenario since the example provided below may not work as intended in this context.

HTML Example:

<table>
    <tbody>
        <tr>
            <td>
                <input class="txtInput" type="text" name="test1" value="test1val" readonly/>
            </td>
            <td>
                <input type="button" class="btnEdit" name="editName" value="Edit"/>
            </td>
        </tr>
        <tr>
            <td>
                <input class="txtInput" type="text" name="test2" value="test2val" readonly />
            </td>
            <td>
                <input type="button" class="btnEdit" name="editName" value="Edit" />
            </td>
        </tr>
    </tbody>
</table>

JQuery Functionality:

$(document).ready(function () {
    $('.btnEdit').click(function () {
        if ($('.txtInput').prop('readonly')) {
            $('.txtInput').removeAttr('readonly');
        }
        else {
            $('.txtInput').attr('readonly', 'readonly')
        }
    });
});

Page Preview:

https://i.sstatic.net/0bnMw.png

Answer №1

To access the input in the previous TD when a button is clicked, you can utilize jQuery

$(document).ready(function () {
    $('.btnEdit').on('click', function () {
        $('table .txtInput').prop('readonly', true);
        var elem = $(this).closest('td').prev('td').find('.txtInput');
        elem.prop('readonly', function(_,state) { return !state });
    });
});
input[readonly] {color: red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tbody>
        <tr>
            <td><input class="txtInput" type="text" name="test1" value="test1val" readonly/></td>
            <td><input type="button" class="btnEdit" name="editName" value="Edit" /></td>
        </tr>
        <tr>
            <td><input class="txtInput" type="text" name="test2" value="test2val" readonly /></td>
            <td><input type="button" class="btnEdit" name="editName" value="Edit" /></td>
        </tr>
    </tbody>
</table>

Answer №2

To assign a custom data attribute to each button, I recommend the following approach:

       <td><input class="txtInput" type="text" id="test2" name="test2" value="test2val" readonly /></td>
        <td><input type="button" class="btnEdit" data-attr-target="test2" name="editName" value="Edit" /></td>

Then in the click handler function, you can retrieve this custom attribute.

$('.btnEdit').click(function(){
    var target = $(this).data('attr-target');
    var input = $(target);
    input.attr('readonly', readonly);
});

If your elements are being dynamically generated, you can still handle this by using dynamic ids like "inputName_index" when creating the inputs.

Answer №3

In my approach, I would handle the code slightly differently compared to adeneo. First, I would locate the closest row and then retrieve the text using the following method:

$(document).ready(function () {
    $('.btnEdit').on('click', function () {

        var element = $(this).closest('tr').find('.txtInput');
        element.prop('readonly', function(_,state) { return !state });
    });
});

Alternatively, you could assign an attribute to the button with the ID of the textbox you wish to modify. This would require changes in the HTML structure to include IDs:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tbody>
        <tr>
            <td><input class="txtInput" id='txt1' type="text" name="test1" value="test1val" readonly/></td>
            <td><input type="button" txtid='#txt1' class="btnEdit" name="editName" value="Edit" /></td>
        </tr>
        <tr>
            <td><input class="txtInput" id='txt2' type="text" name="test2" value="test2val" readonly /></td>
            <td><input type="button" txtid='#txt2' class="btnEdit" name="editName" value="Edit" /></td>
        </tr>
    </tbody>
</table>

The corresponding JavaScript code would be:

$(document).ready(function () {
    $('.btnEdit').on('click', function () {
        var txtid = $(this).attr('txtid');
        $(".txtInput").each(function(){
              if ($(this).attr('id')!=txtid)   
              {
                  $(this).prop('readonly',true);
              }
        });
        var element = $();
        element.prop('readonly', function(_,state) { return !state });
    });
});

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

Using the Jquery .each() method with Flickr JSON data

When looping over the JSON data returned from Flickr, I expected to alert 0, 1, 2, 3... for the index. However, it is actually alerting id, server, farm, etc. $.each(data.photo, function(index,item){ alert(index); }); UPDATE: By the way, I am utiliz ...

PHP - Implementing a Submit Button and Modal Pop-up AJAX across multiple browsers in PHP

As a newbie in PHP AJAX coding, I'm facing a challenge with having two browsers. My goal is to click the submit button on one browser and have a modal popup on the other browser simultaneously. Essentially creating a chat system where only a button an ...

Code Wizard

I am currently working on a project to develop an HTML editor. How it Needs to Function Elements Inside: Text Area - Used for typing HTML as text Iframe - Displays the typed HTML as real [renders string HTML to UI] Various Buttons Functionality: When ...

Displaying a vertical arrangement of collapsed menu items with a centered navbar and logo positioned at the center of it (using bootstrap)

I'm currently working on a website that features a centered navbar with a logo also centered inside it. The tech I'm using is Bootstrap and LESS. Issue When the navbar collapses on mobile/tablet view, the menu items are displayed horizontall ...

How to Insert JSON into React Component's Attribute?

I am struggling with setting the value of a React component using JSON in the attribute. I want to concatenate a letter or word, but it doesn't seem to work. Is there a correct way to combine strings within a Component's attribute? In this case, ...

Guide on displaying an EJS page with AngularJS on a Node.js server

Having an issue with rendering an ejs page through nodejs. The page works fine independently, but fails to load when rendered via nodejs. Any help would be appreciated. ejs page: <html> <script src="/home/aniruddha/Downloads/angular.js"></ ...

"Implementing a right-aligned dropdown menu in the navbar using Bootstrap 4

I am encountering an issue with the dropdown menu in Bootstrap 4. Here is my code snippet: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/font-awesom ...

The Express server automatically shuts down following the completion of 5 GET requests

The functionality of this code is as expected, however, after the fifth GET request, it successfully executes the backend operation (storing data in the database) but does not log anything on the server and there are no frontend changes (ReactJS). const ex ...

Guide on adjusting padding for jQuery Flot graph for improved styling

I am utilizing jQuery Flot to generate a basic graph. I do not want the axes to display on either side, but this is causing the points to be slightly cut off. Any suggestions on how to resolve this issue? $.plot('#'+id, [ { data: data.values ...

Having trouble with clearing floats in Twitter Bootstrap CSS - any help appreciated!

Today, in an effort to learn CSS and apply it practically by creating simple themes, I decided to delve into the proper ways of clearing floats in CSS. My research led me to explore how Twitter handles this issue, so I dug into Bootstrap's CSS file an ...

Steps to prevent cart resizing in desktop view:

For a front-end challenge, I need you to design a simple card that displays consistently in both mobile and desktop views. I took a mobile-first approach because I've encountered issues where the card layout changes when viewed on desktop. Check out ...

What is the best way to include rxjs in an npm library - as a dependency, peer dependency, or both?

After researching numerous posts and articles on dependencies versus peerDependencies, I am still not entirely certain what to do in my particular situation.... I have a library (which is published to a private npm repository) that utilizes rxjs; for exam ...

Utilizing AngularJS to show content based on regular expressions using ng-show

With two images available, I need to display one image at a time based on an input regex pattern. Here is the code snippet: <input type="password" ng-model="password" placeholder="Enter Password"/> <img src="../close.png" ng-show="password != [ ...

Obtain JSON information from DataTables in a column-by-column manner

I am currently working with a Datatable displayed below <table id="example" class="display" width="100%" cellspacing="0"> <thead> <tr> <th>Name</th> <th>Position</ ...

Circular arrangement using D3 Circle Pack Layout in a horizontal orientation

I'm currently experimenting with creating a wordcloud using the D3 pack layout in a horizontal format. Instead of restricting the width, I am limiting the height for my layout. The pack layout automatically arranges the circles with the largest one ...

Unable to retrieve the value of a clicked button using jQuery

i am attempting to extract an array from checked buttons when a button is clicked. Although I can successfully retrieve the array, I am struggling to obtain the value of the clicked button. the code snippet below illustrates my attempt: $('.multiple& ...

Slide both divs simultaneously from left to right

Is there a way to simultaneously hide and show div elements, without having to wait for the effect to take place? Here is my current code: $('a').on('click', function(){ var div_hide = $(this).parent(); var div_show = $(this). ...

Tips for optimizing the placement of div elements for top advertisements on Amazon's website

I'm looking to overlay some divs on top of Amazon.com ads, similar to the image above. This is part of a personal project where I need to position these divs precisely over the ads. To achieve this effect, I've been using getBoundingClientRect t ...

I need assistance with a feature on my website where a new form is added every time the invite button is clicked, and the form is deleted when the delete button is

Invite.js This invite component includes an invite button outside the form and a delete button inside the form. The goal is to delete the form when the delete button is clicked. I have utilized useState and sourced this form from material-ui. Can anyone ...

Troubleshoot remote debugging in WebStorm when using Nodemon

Utilizing Nodemon has significantly increased my development speed by automatically restarting my app whenever I make changes. Due to the inability of WebStorm debug to work seamlessly with Nodemon using standard methods (%NODE_DEBUG% or --debug-brk), I h ...