Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to confirm and call function with onclick

Can I call JavaScript function with return confirm(); in HTML onclick event or do I need to do function which contains confirmation and call to another function?

<button onclick="return confirm('Are you sure?'); saveandsubmit(event);"></button>

Thanks in advance.

like image 337
lingo Avatar asked Sep 04 '15 09:09

lingo


People also ask

How do you call a function on a click button?

To invoke this function in the html document, we have to create a simple button and using the onclick event attribute (which is an event handler) along with it, we can call the function by clicking on the button.

Can I call two function onclick?

Yes, you can call two JS Function on one onClick.

Is Onclick a callback?

We can create an HTML button element and use the native onclick event. The value of this event will be a callback function activateLasers() . So when the button is clicked, activateLasers() is also called and adds an alert to our screen.

Can we use Onclick in anchor tag?

Using onclick Event: The onclick event attribute works when the user click on the button. When mouse clicked on the button then the button acts like a link and redirect page into the given location. Using button tag inside <a> tag: This method create a button inside anchor tag.


2 Answers

Add if condition

<button onclick="if(confirm('Are you sure?')) saveandsubmit(event);"></button>

OR

<button onclick="return confirm('Are you sure?')?saveandsubmit(event):'';"></button>
like image 113
Man Programmer Avatar answered Oct 24 '22 18:10

Man Programmer


Try below :

<button onclick="confirm('Are you sure ?') && saveAndSubmit(event)">Button</button>


function saveAndSubmit(event){
    alert('saveAndSubmit called !');
}

JSFiddle : https://jsfiddle.net/nikdtu/cyt955bp/

like image 26
Nikhil Maheshwari Avatar answered Oct 24 '22 17:10

Nikhil Maheshwari