Search code examples
javascriptjqueryjquery-events

Handle JavaScript function inside loop


I am using JavaScript function inside of while loop. That loop prints list of records and edit button. When click on edit button there is function (Lets say editBtnClicked(id)). Problem: It is getting called to there but page is refreshing automatically.

What is happening over there I couldn't find? Someone have a look at this:

function editBtnClicked(id) {
                console.log("Edit Section");
                $(".showData").css("display", "none");
                $(".showInputField").css("display", "block"); }

<button id="edit" name="Edit" value="Edit" class="edit btn btn-info"onclick="editBtnClicked('<%=id%>');">

Solution

  • By defualt, button elements are type="submit". If you don't want it to be a submit button, use type="button" instead:

    <button type="button" id="edit" name="Edit" value="Edit" class="edit btn btn-info"onclick="editBtnClicked('<%=id%>');">
    

    If for some reason you want it to continue to be a submit button, but you want to prevent submission: In your onclick attribute, pass the event into your function:

    <button id="edit" name="Edit" value="Edit" class="edit btn btn-info"onclick="editBtnClicked(event, '<%=id%>');">
    

    That event will exist within the context created for that call, either as a global (Chrome, IE) or as a local (Firefox).

    Then in your handler, use preventDefault:

    function editBtnClicked(event, id) {
        $.Event(event).preventDefault(); // Note the jQuery event wrapper
        console.log("Edit Section");
        $(".showData").css("display", "none");
        $(".showInputField").css("display", "block");
    }
    

    That said, I'd probably change this up completely and use event delegation instead of an onclick attribute.

    On some container all these buttons will be in:

    $("selector for the container").on("click", "button.edit", editBtnClicked);
    

    ...and when outputting them (note I've removed the id — you said this was a loop, you can't have the same id more than once!):

    <button type="button" type="button" value="Edit" class="edit btn btn-info" data-id="'<%=id%>'">
    

    And in the function:

    function editBtnClicked() {
        var id = $(this).attr("data-id"); // Get the ID
        console.log("Edit Section");
        $(".showData").css("display", "none");
        $(".showInputField").css("display", "block");
    }