kebabTiger
kebabTiger

Reputation: 652

onClick only works for first button in table

I'm trying to make a dynamic table in which each row in the table has a "modify" button that pops up a modal in which will have a form requesting information.

here is my current CSHTML code:

<body>
    <div id="container">
        <h1>Fingerprint Tool</h1>
        <form id="userIdForm" method="post">
            Type in your UserId: <input name="userId" type="number" id="formUserId" />
            <input type="submit" />
        </form>

        @if (Model != null)
        {
            <h2>List of Fingerprints for user</h2>
            <div id="tableDiv">
                <table class="fingerprintTable">
                    <thead>
                        <tr>
                            <th>User ID</th>
                            <th>Fingerprint ID</th>
                            <th>FingerprintGrant ID</th>
                            <th>PaymentType ID</th>
                            <th>Fingerprint</th>
                            <th>IsDeleted</th>
                            <th>Status ID</th>
                            <th>Created Date</th>
                            <th>Updated Date</th>
                            <th>Modify</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var fingerprint in Model.Fingerprints)
                        {
                            <tr>
                                <td id="userId">@fingerprint.UserId</td>
                                <td id="fingerprintId">@fingerprint.FingerprintId</td>
                                <td id="fingerprintGrantId">@fingerprint.FingerprintGrantId</td>
                                <td id="paymentTypeId">@fingerprint.PaymentTypeId</td>
                                <td id="fingerprint">@fingerprint.Fingerprint</td>
                                <td id="isDeleted">@fingerprint.IsDeleted</td>
                                <td id="fingerprintStatusId">@fingerprint.FingerprintStatusId</td>
                                <td id="createdDate">@fingerprint.CreatedDate</td>
                                <td id="updatedDate">@fingerprint.UpdatedDate</td>
                                <td><button id="modifyButton" onclick="modifyFingerprintInfo(@fingerprint.FingerprintId);">Modify</button></td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>

            <div id="myModal" class="modal">

                <!-- Modal content -->
                <div class="modal-content">
                    <span class="close">x</span>
                    <p id="modalHeader"></p>
                </div>

            </div>
        }
    </div>
</body>

Here is my JS file:

    window.onload = function() {
        $(".modifyButton")
        .click(function() {
            modifyFingerprintInfo($(this).data("fpid"));
        });
    }

    function modifyFingerprintInfo(fingerprintId) {
    // call updateStatus hermes endpoint

    // Get the modal
    var modal = document.getElementById("myModal");
    // Get the button that opens the modal
    var btn = $(".modifyButton");
    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];
    // When the user clicks on the button, open the modal 

    // When the user clicks on <span> (x), close the modal
    span.onclick = function () {
        modal.style.display = "none";
    }
    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function (event) {
        if (event.target === modal) {
            modal.style.display = "none";
        }
    }
    $("#modalHeader").text("Update the status of FingerprintId " + fingerprintId);

}

And here is my CSS code:

.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 15% auto; /* 15% from the top and centered */
    padding: 20px;
    border: 1px solid #888;
    width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}

#container {
    width: 100%;
    position: absolute;
    left: 4px;
}

The problem is that when I click on the Modify button in each row, the first time I click, nothing happens, and then the second time it works, but only for the first button in the first row. On top of that, for example if I click on row 4 Modify button, nothing will happen, but when I click on row 1 modify button, it prints out row 4's details.

I'm not sure what's going on, so any help would be greatly appreciated!

Upvotes: 2

Views: 9530

Answers (2)

Eduardo Mioto
Eduardo Mioto

Reputation: 144

considering that your main intention, you are intending to locate a button on a dynamic table, so to be able to execute this action your id also needs to be dynamic.

Let's supposed that @fingerprint.UserId is a unique and will not be repeated on your listing. Having this unique identifier you may do the following:

<button id="[email protected]">Modify</button>

And, consequently you will need to update your function to be triggered properly and extract the unique identifier from button id. A possible solution could be use a jquery selector to create this dynamism.

Ref: https://api.jquery.com/id-selector/

Ref: https://api.jquery.com/attribute-starts-with-selector/

$( "button[id^='modifyButton_']" ).(function);

Considering that your function is being properly triggered, now you are able to extract from your button id the reference for your data on table.

Ref: https://api.jquery.com/click/

var userId = $(this).attr("id").replace("modifyButton_"); 

Considering this solution you can also populate your modal with dynamic content, improving the UX.

I hope that it can help you to improve your solution. In case of doubts, please let me know.

Upvotes: 1

Lifz
Lifz

Reputation: 688

You can use class instead of id for identifying more than one element. The id attribute is intended to be used for a single element and if more than one has the same id, only 1 will be selected.

Secondarily, you don't want to be setting click event handlers inside of click event handlers. Let's do it all at once.

I see you have this question tagged with jQuery so you can use:

<button class="modifyButton" data-fpid="1111">Modify</button>

$(".modifyButton").click(function() {
    $("#modalHeader").text("Update the status of FingerprintId " + $(this).data("fpid");
    $("#myModal").show();
});

This shows that by using id, only the first one fires:

$("#button").click(function() {
  alert($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Clicked button ONE</button><br /><br />
<button id="button">Clicked button TWO</button><br /><br />
<button id="button">Clicked button THREE</button>

This shows that by using class, any of them fire:

$(".button").click(function() {
  alert($(this).data("fpid"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button" data-fpid="111">Clicked button ONE</button><br /><br />
<button class="button" data-fpid="222">Clicked button TWO</button><br /><br />
<button class="button" data-fpid="333">Clicked button THREE</button>

Upvotes: 10

Related Questions