Issue with validation on dynamically inserted rows has not been resolved

I am a beginner to jQuery and I have implemented validation for input fields. I am also dynamically generating input fields when the add row button is clicked. However, I have assigned the same id value to all input fields and the validation is not working for the newly generated rows when I click the button.

Can anyone help me identify where I went wrong? Thank you in advance.

$(document).ready(function () {
    $("#mobile").keypress(function (e) {
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
    });
});


$(document).on('click', '#add_row', function () {

    var a = $("#name").val();
    var b = $("#country").val();
    var c = $("#mail_id").val();
    var d = $("#mobile").val();


    if (a == "") {
        $("#name").addClass("error");
    }
    else {
        $("#name").removeClass("error");
    }

    if (b == "") {
        $("#country").addClass("error");
    }
    else {
        $("#country").removeClass("error");
    }

    if (c == "") {
        $("#mail_id").addClass("error");
    }
    else {
        $("#mail_id").removeClass("error");
    }

    if (d == "") {
        $("#mobile").addClass("error");
    }
    else {
        $("#mobile").removeClass("error");
    }

    var i = 1;
    if (a == '' || b == '' || c == '' || d == '') {
        i = 1;
    }
    else {
        $('#addr' + i).html("<td><input name='checkbo" + i + "' type='checkbox' placeholder='' class='check'  /></td><td><input name='name" + i + "' type='text' placeholder='Name' class='form-control input-md' id='name'/> </td><td><select name='country" + i + "' class='form-control' id='country'><option value=''>select an option</option><option value='afghan'>Afghanistan</option><option value='albania'>Albania</option></select></td><td><input  name='mail" + i + "' type='text' placeholder='Mail'  class='form-control input-md'  id='mail_id'></td><td><input  name='mobile" + i + "' type='text' placeholder='Mobile'  class='form-control input-md' id='mobile'></td>");

        $('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
        i++;
    }

    $("#delete_row").click(function () {
        if (i > 1) {
            $("#addr" + (i - 1)).html('');
            i--;
        }
    });
});
.error{
    border: 1px solid red;
    transition: border-color .25s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
            <div class="row clearfix">
                <div class="col-md-12 column">
                    <table class="table table-bordered table-hover" id="tab_logic">
                        <thead>
                            <tr >
                                <th>

                                </th>
                                <th class="text-center">
                                    #
                                </th>
                                <th class="text-center">
                                    Name
                                </th>
                                <th class="text-center">
                                    Address
                                </th>
                                <th class="text-center">
                                    Mobile
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr id='addr0'>
                                <td>
                                    <input type="checkbox" class="check_0">
                                </td>
                                <td>
                                    <input type="text" name='name0'  placeholder='Name' class="form-control name" id="name" required>
                                </td>
                                <td>
                                    <select id="country" name="country" class="form-control"> 
                                        <option value="">select an option</option>
                                        <option value="Afghanistan">Afghanistan</option>
                                        <option value="Albania">Albania</option>
                                    </select>
                                </td>
                                <td>
                                    <input type="text" name='mail0' class="form-control" id="mail_id" required>
                                </td>
                                <td>
                                    <input type="text" name='mobile0' placeholder='Mobile' class="form-control" id="mobile" required>
                                </td>
                            </tr>
                            <tr id='addr1'></tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <a id="add_row" class="btn btn-default pull-left">Add Row</a><a id='delete_row' class="pull-right btn btn-default">Delete Row</a>
        </div>

Answer №1

It is important to avoid assigning the same id to multiple inputs as each id should be unique.

To validate a group of inputs, assign them all the same class name like so:

$().ready(function() {
    $('#div1').hide();
    $('#btn1').click(function() {
        $('.class1').each(function() {
            $('#div1').hide();
            if ($(this).val() == "") {
                $('#div1').show();
                return false;
            }
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="div1">Error</div>
<input class="class1"/>
<input class="class1"/>
<input class="class1"/>
<button id="btn1">Click here</button>

This method will also work for dynamically added inputs.

Answer №2

It is crucial to avoid using the same IDs for fields in your code. Each ID should be unique for different fields.

According to XHTML 1.0 Spec,

In XML, fragment identifiers are of type ID, and there can only be a single attribute of type ID per element. Therefore, in XHTML 1.0 the id attribute is defined to be of type ID. XHTML 1.0 documents MUST use the id attribute to define fragment identifiers on specific elements to ensure well-structured XML documents. Refer to the HTML Compatibility Guidelines for backward compatibility with XHTML documents served as text/html.

I have revised your code for better functionality. Here is a demo link to see the changes in action:

https://jsfiddle.net/4onh3nrx/1/

HTML

<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-bordered table-hover" id="tab_logic">
                <thead>
                    <tr >
                        <th>

                        </th>
                        <th class="text-center">
                            #
                        </th>
                        <th class="text-center">
                            Name
                        </th>
                        <th class="text-center">
                            Address
                        </th>
                        <th class="text-center">
                            Mobile
                        </th>
                        <th class="text-center">
                            Action
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <tr id='addr0'>
                        <td>
                            <input type="checkbox" class="check_0">
                        </td>
                        <td>
                            <input type="text" name='name0'  placeholder='Name' class="form-control name" id="name" required>
                        </td>
                        <td>
                            <select id="country" name="country" class="form-control country"> 
                                <option value="">select an option</option>
                                <option value="Afghanistan">Afghanistan</option>
                                <option value="Albania">Albania</option>
                            </select>
                        </td>
                        <td>
                            <input type="text" name='mail0' class="form-control mail_id" id="mail_id" required>
                        </td>
                        <td>
                            <input type="text" name='mobile0' placeholder='Mobile' class="form-control mobile" id="mobile" required>
                        </td>
                        <td>
                            <a href="#" class="btn btn-warning add-row">
                                <i class="glyphicon glyphicon-plus"></i>
                            </a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <a id="add_row" class="btn btn-default pull-left">Add Row</a><a id='delete_row' class="pull-right btn btn-default">Delete Row</a>
</div>

JS

<script>
    $(document).ready(function () {
        $("#mobile").keypress(function (e) {
            if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                return false;
            }
        });
    });

    $(document).on('click', '.delete-row', function(){
        $(this).closest('tr').remove();
    });

    $(document).on('click', '.add-row', function(){
        var tr = $(this).closest('tr');
        var field = [
            '.name', '.country', '.mail_id', '.mobile'
        ];
        console.log(tr);
        var flag = false;
        for(var i = 0; i < field.length; i++) {
            var ele = $.trim($(tr).find(field[i]).val());
            console.log(ele);
            console.log($(tr).find(field[i]));
            if(!ele.length) {
                flag = true;
                $(tr).find(field[i]).addClass('error');
            } else {
                $(tr).find(field[i]).removeClass('error');
            }
        }

        if (!flag) {
            var html = "<tr><td><input name='checkbo" + i + "' type='checkbox' placeholder='' class='check'  /></td><td><input name='name" + i + "' type='text' placeholder='Name' class='form-control name input-md'/> </td><td><select name='country" + i + "' class='form-control country'><option value=''>select an option</option><option value='afghan'>Afghanistan</option><option value='albania'>Albania</option></select></td><td><input  name='mail" + i + "' type='text' placeholder='Mail'  class='mail_id form-control input-md'></td><td><input  name='mobile" + i + "' type='text' placeholder='Mobile'  class='form-control input-md mobile'></td><td><a href='#' class='btn btn-warning add-row'><i class='glyphicon glyphicon-plus'></i></a><a href='#' class='btn btn-danger delete-row'><i class='glyphicon glyphicon-minus'></i></a></td></tr>";
            $(html).insertAfter(tr);
        }
    });
</script>

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 functions like nl2br() for new line breaks, preg_replace for replacing patterns, htmlspecialchars() for encoding special

I've reviewed all the answers on this topic, but I'm still struggling to find the correct method for sanitizing data. My task is to enter: <?php echo 'yes'; ?> <?php echo 'yes' ?> into a text area, submit it in ...

How can you make a dropdown button interactive and display a list simultaneously?

I'm facing an issue with lines 45-47 in the second link. If that code is present, the button animates when clicked (which is great) BUT the dropdown items ("About," "Archive," "Contact") do not appear. If I remove lines 45-47, the dropdown items appea ...

What strategies can be employed to utilize JSON data for populating two distinct views?

In my Rails application, I have two view ports that display the same data. The JSON format for retrieving this data looks like: $.read( '/en/search/fetch_companies', { current_location_lat: 72, current_location_lng: 10, bounding_box: 10 ...

Determining the exact number of immediate descendants within a ul element, while disregarding any script elements

Here is the HTML structure I am working with, which contains a script tag: <ul id="list"> <li class="item1"><a href="#">Item 1</a></li> <li class="item2"><a href="#">Item 2</a></li> <li ...

The FileReader.result is found to be null

Currently, I am in the process of setting up a page that allows users to upload a txt file (specifically a log file generated by another program) and then modify the text as needed. Initially, my goal is to simply console.log the text, but eventually, I pl ...

Failure to prepare mySQLi statement due to multiple question marks being used in the form

Hello, I am currently working on implementing a multi field search feature. The form consists of four fields and the user has the flexibility to input information into one or more fields for querying the database. While the SQL query functions correctly i ...

Track and maintain the active status of the clicked article using jQuery

I'm encountering an issue with jQuery where the parent ul li does not open as expected. Below is the structure of my HTML: <div> <ul> <li class="has-sub"> <a href="#">1</a> <ul> &l ...

Issues with Bootstrap tabs loading jQuery and Ajax are preventing the proper functionality

I am currently facing an issue with a tab pane designed using Bootstrap. The problem arises when attempting to load external pages into the tabs through Ajax using a jQuery script. While the ajax script successfully loads the content of the pages, I am en ...

Simple Guide to Inserting Items in a Column with Flexbox and Material UI

I've been struggling to position these items on the modal and could use some advice. I'm aiming to include the item counter as text and stars below it, with the unassigned text at the bottom. Despite trying various layouts, I can't seem to g ...

How to customize the hover and active properties of a checked checkbox in Vue 3 using Tailwind CSS and PUG?

It seems that checkboxes have a level of sophistication that I never anticipated, or perhaps my brain just can't quite grasp the nuances of checkboxes. After spending a significant amount of time researching and experimenting with checkboxes in a Vue ...

Leveraging the power of beautifulsoup and selenium for web scraping on a multi-page site results in gathering a

I am in the process of scraping text from a website iteratively. Each page on this particular website follows the same html structure. I utilize selenium to go to the next page each time I add the following strings: text_i_want1, text_i_wantA, text_i_wantB ...

Using the filter() function in jQuery allows for efficient sorting and

My current area of study is in jQuery, but I'm encountering a bit of confusion with the following code: var list = mylist.filter(function(f) { return $(f) .find('.anthing') .length > 0; }); I'm particularly puzz ...

The delay in loading HTML content using FOSJsRoutingBundle and Ajax for a specific route parameter (ID)

I'm using FOSjSrouting in my symfony2.7 project. This is the code in my html.twig view: <table> <!--table header code ...etc... --> <tbody> {% for currentData in arrayData %} <tr> <td>{{ currentData. ...

"Learn the technique of adding a new data attribute before every element in a step-by-step

I am currently working with the following HTML code: <div id="elem"> <div data-foo="aaa"></div> <div data-foo="aaa"></div> <div data-foo="aaa"></div> <div data-foo="bbb"></div> < ...

Internet Explorer fails to execute CSS or jQuery commands

Apologies in advance for posing a question that may not be specific or beneficial to the wider community. Currently, my main focus is resolving this issue for my own peace of mind. In the process of designing a website, I implemented a social drawer featu ...

Is there a way for me to automatically go back to the home page when I press the back button on the browser?

My ecommerce website has a shopping cart page where customers can purchase products and make payments. After the payment is completed, they are directed to a thank you page. The flow of the website is as follows: Home page => Products => Shopping ca ...

Tips for aligning input elements in the center using HTML and CSS

https://i.sstatic.net/3B7F9.jpg Can someone help me center the input vertically within the image? I'm not sure how to achieve this. .headmenu { background-color: rgb(47, 47, 47); width: auto; height: 30px; } .headmenu-right { float: right ...

What could be causing my line-clamp to malfunction when using a fixed height in the Safari browser?

I have a problem with the design of my episode list on mobile devices. The list has a fixed height, and I am using the line-clamp-2 property for the episode titles that exceed two lines. While everything looks fine on my PC and even when using Dev Tools t ...

Positioning with Bootstrap CSS libraries

The text next to the logo in the navbar isn't aligning properly (refer to this link for the page -> ). Furthermore, the logo isn't positioning correctly either, and this issue is present in all the navbar codes. I'm utilizing CSS bootstr ...

Tips for wrapping text around an image using Bootstrap 5

I am having trouble getting my text to wrap around an image using the Bootstrap 5 grid system. I've attempted to use 'float: right' on the image, but it hasn't produced the desired result. The text should flow naturally around the imag ...