hjardine
hjardine

Reputation: 495

JQuery function to fire only once

I know this is a commonly asked question but I have not found a solution to the problem I have.

I have a table with a loop of buttons to edit each particular tr, when the button is pressed it loads a partial view with a form and then when pressed again populates the form's text areas with the users details and I set a .one function so that the partial is only loaded the first time the buttons clicked, this works fine.

However when a button is pressed on another user, instead of populating the existing text area with the new users details it calls the partial view again which shows blank so you have to click twice on each user every time you want to display there details which is very annoying.

Table

    <table class="table">
    <thead>
        <tr>
            //Table Headers
        </tr>
    </thead>
    <tbody>
        <!-- Render the details of each employee. -->
        @foreach (var item in Model)
        {
            <tr>
                <td><input type="button" class="btn btn-primary editUser" id="editUser" name="editUser" value="Edit" onclick="Hide_Div(NewUserDiv)" /></td>

                //Some @Html.DisplayFor() calls

            </tr>
        }
    </tbody>
</table>

JQuery

$(".editUser").one("click", function editUsers() {
        $.ajax({
            url: '/Home/EditUser',
            success: function (data) {
                $('#EditUserDiv').html(data);
            }
        });
    });

//This section is repeated numerous times for each value username/email etc.
$(".editUser").click(function () {
        //find details
            $('#txtUL').empty().append(insertText)
        });
    });

As you can see I have a .onefunction but as the button is in a loop (Table/tbody/tr) the .one function applies to each button.

If you need me to clarify anything or you want any more details please ask. Thanks in advance.

P.S everything works but i would like to make it so the

$(".editUser").one("click", function editUsers() {
        $.ajax({
            url: '/Home/EditUser',
            success: function (data) {
                $('#EditUserDiv').html(data);
            }
        });
    });

applies to all of the .editUser buttons together rather then each individually so once the partial page is uploaded it doesn't upload again.

Upvotes: 1

Views: 164

Answers (1)

Jamiec
Jamiec

Reputation: 136094

If I understand this right you need a boolean to indicate the action has taken place (and therefore not to do it again)

var isEditingUser = false;
$(".editUser").one("click", function editUsers() {
   if(isEditingUser) return;

    $.ajax({
        url: '/Home/EditUser',
        success: function (data) {
            isEditingUser = true;
            $('#EditUserDiv').html(data);
        }
    });
});

Upvotes: 1

Related Questions