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

Is it possible to utilize global variables within CSS properties?

I have a scenario where I need to dynamically change values in an animation. The line of code that needs modification is: clip-path: polygon(var(clip1) 0, 100% 1%, 100% 100%, 50% 100%); let root = document.documentElement; root.style.setProperty('c ...

Organizing Results into Divs Based on Column Value Using AngularJs

I've been racking my brain trying to figure out the best way to organize and display my results in separate divs, specifically using Bootstrap col-md-4's. This is for a chat messaging app that I'm in the process of developing. I have rooms a ...

Refusing to conceal content within Outlook email

As I work on creating a responsive email template that is compatible with Outlook, I encounter a strange issue. The HTML for Outlook displays correctly, as does the responsive HTML. However, once the email is sent to Outlook, the content becomes duplicated ...

Displaying related data in jqGrid using foreign keys

My jqGrid is connected to a JSON datasource provided by a WCF web service. The WCF method retrieves a list of ids showing the relationship between a user, branch, and role. For instance, a user can have different roles in different branches. [{"entityHash ...

Nested state fails to display HTML content or activate controller initialization

I am trying to utilize ui-router's parent/child states with the code snippet below. Everything seems to be in order as there are no console errors, but for some reason the HTML content is not being rendered and the controller's init function is n ...

Jquery Ajax is failing to transmit the authorization header

Attempting to set up basic authentication using Jquery Ajax. Adding an authorization header to the ajax request as shown below. $.ajax({ headers: { "authorization": "basic 123456", }, crossDomain: true, type: "POST", contentTyp ...

Updating the underline style of ant.d's menu item

Currently, I am working with ant.design to build my navbar. By default, the menu items in ant design have a blue-ish underline when selected or hovered over. However, I want to change this underline color to match the overall design of my project. I was su ...

Troubleshooting border problems with Bootstrap 3 tables

Recently, I encountered a problem with the Bootstrap 3 table-bordered where the right border was not showing up. Below is the code snippet of my table: <table class="table table-bordered table-hover"> ... </table> Upon inspecting the table vi ...

Optimizing Performance by Managing Data Loading in JavaScript Frameworks

I am new to JavaScript frameworks like React and Vue, and I have a question about their performance. Do websites built with React or Vue load all data at once? For example, if I have a page with many pictures, are they loaded when the component is used or ...

Verify the presence of the promotion code and redirect accordingly

I have created a special promotion page that I want to restrict access to only users who have received a unique code from me via email. To achieve this, I have designed the following form: <form accept-charset="UTF-8" action="promotion.php" method="po ...

Having trouble with NVM not working correctly in Ubuntu 21.04 Terminal?

Lately, I've been facing challenges with updating my Node.js version, and one method I tried was using node version manager. After downloading the install_nvm.sh file with the command curl -sL https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/insta ...

Image Blob increases over 50 times its original size when uploaded

I'm completely baffled by the situation unfolding here. Using Preprocess.js, I am resizing/compressing an image on the front-end. During the processfile() function on the image.onload (line 32), I convert the toDataURL() string to a Blob, in order to ...

I possess a single input field and I am seeking to have the focus shifted to it upon the activation of a button

Looking to enhance user input with an icon interaction: Clicking the icon should focus on the input Considering a solution for when clicking the icon to trigger focusout A code snippet has been implemented for the first requirement, seeking suggestions ...

What is the best way to see if a variable is present in TypeScript?

I am facing an issue with my code that involves a looping mechanism. Specifically, I need to initialize a variable called 'one' within the loop. In order to achieve this, I first check if the variable exists and only then proceed to initialize it ...

Material-UI's simplification of 10px comprehension

I'm a bit confused about why we have to do this for the 10px simplification: html { font-size: 62.5%; /* 62.5% of 16px = 10px */ } Shouldn't the following code handle everything? const theme = createMuiTheme({ typography: { // Set the ...

Get the name of the array using JavaScript

Here is an example of my situation: var list1 = ['apple', 'banana', 'orange']; var list2 = ['carrot', 'lettuce', 'tomato']; When I use: alert(list1) I get: apple, banana, orange. This is corre ...

gallery showcasing pictures with a prominent main image and accompanying smaller images

I am struggling to display my image gallery the way I envision it. I would like to have a larger main image with the rest of the images displayed on the right side below it. The current code I have is: <div class="gallery"> <a href=" ...

Refresh the JavaScript graph with new data from the AJAX request

Seeking assistance in updating my javascript chart data using ajax data retrieved from a database. The specific chart being referenced is an apex chart. After submitting a form via ajax, the returned result is as follows: type: "POST",crossDomain ...

Ensuring proper execution of the next callback function in an Express get request

I am currently running an express server on nodejs with a specific file structure that I need to convert into a list of links. Included below are my recursive functions for dealing with the file structure. Here are the file structure functions: function ...

What are the steps for accessing a server-side WebControl from the client side?

Issue Overview: I am facing a problem with managing different types of input values in my dialog box. Depending on the selection from a dropdown list, the required input could be simple text, a date, or specific data from a database. I have successfully i ...