The functionality of cloning in jQuery may encounter an issue where the text field remains enabled if the user selects an option labeled "other

Currently, I am working on a jQuery clone with my existing code and everything is functioning well.

  1. In the first scenario, if the user selects other from the dropdown menu, the text field becomes enabled.

  2. In the second scenario, when the user clicks the "addmore" button, the div is cloned perfectly with an ID. If the user selects other, both the original and cloned text fields become enabled. This should not happen; only the cloned text field should be enabled.

Below is the current jQuery code being used:

        var i=1;
    $(document).on("click", ".edu_add_button", function () { 
        var i=$('.cloned-row1').length;
        $(".cloned-row1:last").clone(true).insertAfter(".cloned-row1:last").attr({           
            'id': function(_, id) { return id + i },
            'name': function(_, name) { return name + i }
            }).end().find('[id]').val('').attr({ 'id': function(_, id) { return id + i }  
        }); 
        $(".cloned-row1:last").find(".school_Name").attr('disabled', true).val('');
            if(i < $('.cloned-row1').length){
                $(this).closest(".edu_add_button").removeClass('btn_more edu_add_button').addClass('btn_less btn_less1');
            }   
        i++;
        return false; 
    });  

$(document).on('click', ".btn_less1", function (){
    var len = $('.cloned-row1').length;
    if(len>1){
        $(this).closest(".cloned-row1").remove();
    }
});

$(document).on('change', '.txt_schName', function (){
    var cur = $('.txt_schName').index($(this));
    $('.school_Name').eq(cur).val($(this).val())
    if ($(this).val() == "other") {
        $(".school_Name").prop('disabled', false);
         $(".school_Name").val('');
    }else{
        $(".school_Name").prop('disabled', true);

    }
});

 $(document).on('change', '.txt_degreName', function (){
    var cur = $('.txt_degreName').index($(this));
    $('.degree_Description').eq(cur).val($(this).val())
     if ($(this).val() == "other") {
        $("#degree_Description").prop('disabled', false);
         $("#degree_Description").val('');
    }else{
        $("#degree_Description").prop('disabled', true);
    }
}); 

Access the fiddle via this link.

I would appreciate any suggestions or advice.

Thank you!

Answer №1

DEMO

The problem arises from directly using a class selector. It is important to only apply the value to the text box that is in the same container. Utilize closest() to locate the parent element.

$(document).on('change', '.txt_schName', function (){
    var cur = $('.txt_schName').index($(this));
    var container = $(this).closest('.container-fluid');
    $('.school_Name').eq(cur).val($(this).val())
    if ($(this).val() == "other") {
        $(".school_Name", container).prop('disabled', false);
        $(".school_Name", container).val('');
    } else {
        $(".school_Name", container).prop('disabled', true);
    }
});

Answer №2

CHECK OUT THE LIVE DEMO

Make sure to reference the correct element that needs to be disabled and enabled.

To disable the input element which is a sibling of the parent of a select element, use the following code snippet:

$(document).on('change', '.txt_schName', function (){
        var cur = $('.txt_schName').index($(this));
        $(this).closest('.col-xs-6').next('.col-xs-6').find('.school_Name').eq(cur).val($(this).val())
        if ($(this).val() == "other") {
             $(this).closest('.col-xs-6').next('.col-xs-6').find(".school_Name").prop('disabled', false);
             $(this).closest('.col-xs-6').next('.col-xs-6').find(".school_Name").val('');
        }else{
            $(this).closest('.col-xs-6').next('.col-xs-6').find(".school_Name").prop('disabled', true);

        }
    });

Answer №3

By making the changes you did, all fields with the class .school_Name were altered. To target only the current div, you can include

$(this).parents(".row").find(".class_name")
.

$(document).on('change', '.txt_schName', function (){
    var cur = $('.txt_schName').index($(this));
    $('.school_Name').eq(cur).val($(this).val())
    if ($(this).val() == "other") {
        $(this).parents(".row").find(".school_Name").prop('disabled', false);
        $(this).parents(".row").find(".school_Name").val('');
    }else{
        $(this).parents(".row").find(".school_Name").prop('disabled', true);

    }
});

SEE DEMO HERE

Answer №4

If you want to target a specific item using parent() and next() selector, it's best practice to access the specific field instead of using index (such as eq) for input.

  var schoolObj = $(this).parent().next().find(".school_Name"); 
  schoolObj.val($(this).val());
    if ($(this).val() == "other") {             
       schoolObj.prop('disabled', false);
       schoolObj.val('');
    } else {
       schoolObj.prop('disabled', true);
    }

Check out this Fiddle for reference.

You can learn more about jquery traversing here:

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

Typescript Angular filters stop functioning properly post minification

I developed an angular filter using TypeScript that was functioning properly until I decided to minify the source code. Below is the original filter: module App.Test { export interface IGroupingFilter extends ng.IFilterService { (name:"group ...

Using React and Material-UI: Implementing button functionality to call another class using hooks in the main App component

Just starting out with React/MUI and currently working on different components for a website, so the UI is not a priority at the moment. Encountering an issue when trying to create a button that links to the Sign Up page (similarly for Sign In): Error: ...

Difficulty in managing vertical overflow in a dynamically sized table using Bootstrap

I am facing an issue with the table-responsive class that is causing a scroll on the y-axis even though it is not specified in the CSS. Shown below is a screenshot of the problem, and I have also managed to replicate the bug: <div id="app"> <d ...

Issue with parsley customized error message functionality not functioning as expected

I'm currently dealing with an issue related to the input field below: <input id="name" name="real_name" type="text" placeholder="ie. Your full name or company name" class="form-control input-lg parsley-validated" data-required="true" parsley-er ...

Adjusting the text of a button when hovering over it will also trigger a resizing of the

Currently, I am facing an issue where the bootstrap button's size changes when hovered over. My intention is to have the bootstrap button remain a fixed size while only the text inside it changes using javascript for mouseover and mouseout events. How ...

Troubleshooting a Non-Responsive React onClick Event in ES6

I am a beginner in React and have been searching on various platforms like StackOverflow and the internet, but I cannot figure out why onClick is not working in my case. When I click the button, absolutely nothing happens. I have tried everything from putt ...

Is there a way to regularly extract the most up-to-date HTML code from a dynamic website for designers to work

Our team of designers is responsible for creating graphical mockups, initial html, css, and image sprites for new designs. They also maintain these files. Once the hand-off is complete, our developers then take everything and work it into .Net code, templa ...

How can you create a personalized sorting order using odata?

Within my AngularApp, I retrieve data from a WebAPI using OData queries. All the retrieved results contain both a date and an integer status code. The status codes range from 1 to 4. I am aiming to organize my results in such a way that all items with a ...

I'm having trouble getting onClick to function properly in CodeIgniter

While attempting to utilize onClick in the PHP page as shown below: <a href="javascript:void(0);" onClick="deleteCourse('<?php echo $row->courseId;?>');" class="delete">Delete</a> And in the JavaScript page, the function is ...

Struggling to insert a JavaScript variable into a MySQL database table using PHP and AJAX

As a newcomer to these technologies, I've been struggling all day with what I expected to be a simple task. My goal is to pass a parameter from a JS function to my PHP code using AJAX and then insert that parameter into my database. Here's the J ...

Troubleshooting issues with Vue CLI 4 and A-Frame: Finding solutions for

Recently, I've been working on creating a VR web app using Vue cli 4.2.3 and aframe.io. However, I encountered numerous error messages related to aframe's components. [Vue warn]: Unknown custom element: <a-scene> - did you register the com ...

Localhost causing variations in CSS behavior

I've been working on a website and wanted to share it with someone, so I set up a webserver. However, I've encountered some peculiar behavior when trying to access the site via LAN rather than through my localhost. Firstly, when viewing the site ...

nextAuth.js is failing to access the accessToken, returning only the values {iat, exp, jti} instead

Here is the code I am working with: import NextAuth from "next-auth" import CredentialsProvider from "next-auth/providers/credentials" export default NextAuth({ sectret:process.env.NEXTAUTH_SECRET, session: { strategy: "jw ...

particular shade for button border and background

I'm looking to create a button using Material UI that has a specific design. Right now, I've only been able to achieve this: https://i.stack.imgur.com/xvv7s.png Here is the code I am currently using. If anyone can help me identify what I'm ...

Tips on invoking a Stencil component function or method from beyond the Vue instance

Is it possible to trigger a function in a Stencil component from the parent Vue instance? For example, I would like to call the callChild() method in the Vue instance, which will then trigger the doSomething() function in the Stencil component. The main ...

Monitor responses from ajax POST requests using jQuery

Currently, I am tackling a project involving various ajax actions. The problem arises from the fact that these ajax calls are executed by scripts that I would rather not delve into. In addition, the responses they generate are erratic and lack a consisten ...

Leveraging Angular App with the Bootstrap .modal() JQuery method

I'm encountering issues with Bootstrap 4 and NPM/Angular CLI when using the .modal methods Error: TypeError: $(...).modal is not a function Main.ts: import * as $ from 'jquery'; import * as bootstrap from 'bootstrap'; App.compo ...

Ways to reduce lag while executing a for loop

How can I optimize my prime number generation process to avoid lagging? For example, is there a way to instantly display the results when generating primes up to 1000? HTML: <!DOCTYPE html> <html> <meta name="viewport" content="width=dev ...

"Implementing a feature in React JS react-table to dynamically add a new column when a

I'm struggling to add a new column to react-table when a button is clicked. Even after re-rendering the table with a flag, I can't seem to add the new column. Can anyone suggest where I might be going wrong? Here's the link to the executable ...

javascript hide rows without data

I have a knack for tweaking existing code to suit my needs, but I'm not very proficient in writing my own from scratch. That being said, here's my current dilemma. My pool league uses a Google sheet to manage a variety of statistics, and with so ...