Stop page forwarding to servlet on button click without javascript confirmation

I created a link that sends a request to delete a record to a servlet. I am trying to ask for confirmation before deleting an entry on the same page using javascript. The problem is that I press the Yes or No button to delete the entry. Do I have to make some changes in the servlets or in the javascript so that the request is not redirected to the servlet unless the user clicks the No button and the page stays as it is?

JAVASCRIPT:

function getConfirmation() {
    var retVal = confirm("Do you want to continue ?");
    if (retVal == true) {

        return true;
    } else {

        return false;
    }
}

      

HTML:

<td>
    <div align="center">
        <a href="DeleteController?op=2&from=allResult&id=<%=one.getId()%>" onclick="getConfirmation();">
          Delete
        </a>
    </div>
</td>

      

+3


source to share


3 answers


In your anchor, change onclick to onclick="return getConfirmation();"

<a onclick="return getConfirmation();" href="DeleteController?op=2&from=allResult&id=<%=one.getId()%>">Delete</a>

      




And just return the function confirm()

. It will return true

in OK

, and the default action will be performed; on Cancel

it will return false

and prevent the action.

function getConfirmation(){
   return confirm("Do you want to continue ?");
}

      

Demo

+1


source


You must use

onclick="return getConfirmation();"

      

in your html:



<td>
    <div align="center"><a href="DeleteController?op=2&from=allResult&id=<%=one.getId()%>" onclick="return getConfirmation();">Delete</a></div>
</td>

      

If you want to prevent redirection to any submit button click

, you should always be return false

away from the function.

function getConfirmation() {
    var retVal = confirm("Do you want to continue ?");
    if (retVal) {
        // Ok, do some processing here
        // Your code here
    }

    // To prevent redirection
    return false;
}

      

+3


source


You can load your url in your javascript using assign . One of the templates I found useful is in jQuery document.ready, you can find all tags of a specific type (in this case "link tags"), assign their IDs from the iterator, store the actual url in JSON, and remove it from a real link. This way you can handle everything from Javascript

0


source







All Articles