Hi guys i'm currently working on a delete validate function in javascript. Here is my code.
function confirmDelete(){
var agree = confirm("Are you sure you want to delete this file?");
if(agree == true){
return true
}
else{
return false;
}
}
The alert dialog box comes out but whenever i press "Cancel" button it still deletes the file in the table
Here is my HTML:
<a href=".base_url()."main/delete?id=$row->id>"."<i class='icon-trash' rel = 'tooltip' title = 'Delete' id = 'delete' onClick = 'confirmDelete();'></i></a>";
I'm using CodeIgniter by the way any help will much be appreciated! Thanks guys! :)
try to use return statement where you are calling javascript function.
Like below:
<a href=".base_url()."main/delete?id=$row->id>"."<i class='icon-trash' rel = 'tooltip' title = 'Delete' id = 'delete' onClick = 'return confirmDelete();'></i></a>";
Just do it directly inside your tag:
Delete
Because the on click should be in the <a>, not the <i>. Also, your function could be simplified, considering confirm returns true or false:
function confirmDelete(){
return confirm("Are you sure you want to delete this file?");
}
Call event.preventDefault(), if returning false on its own is not preventing the browser action.
You will need to get a reference to event or window.event.. which is somewhat browser-specific. jQuery or similar can help with this.
onclick="if (! confirm('Are you sure you want to delete this book?')) event.preventDefault();"
(Though, with the above example, we're not returning 'false' any more -- ideally, we'd put the code in a method, and both return false and prevent default if the confirmation is negative.)
To test if it works, most simply:
onclick="event.preventDefault();"
See also:
jQuery: How to get the event object in an event handler function without passing it as an argument?
http://www.quirksmode.org/js/events_access.html
event.preventDefault() vs. return false
The difference between returning 'false' and e.preventDefault() will prevent the default event from occuring,e.stopPropagation()` prevents it from bubbling up/ outwards & outer defaults occurring, but return 'false' does not stop it from bubbling.
So perhaps it would be better to put the onclick handler on the link, which is performing the default action?
Related
I have a button similar to below
<button id="uniqueId" onclick="runMethod(this)">Submit</button>
What I'm trying to do is stop the runMethod from running, until after I've done a check of my own. I've tried using the stopImmediatePropagation function, but this doesn't seem to have worked. Here's my jQuery:
$j(document).on('click', '#uniqueId', function(event) {
event.stopImmediatePropagation();
if(condition == true) {
// continue...
} else {
return false;
}
return false;
});
Note: runMethod basically validates the form, then triggers a submit.
What you want to do, especially in the way that you want to do it, requires a some sort of workaround that will always be a bit fiddly. It is a better idea to change the way the button behaves (e.g. handle the whole of the click event on the inside of the jQuery click() function or something along those lines). However I have found sort of a solution for your problem, based on the assumption that your user will first hover over the button. I am sure you can extend that functionality to the keyboard's Tab event, but maybe it will not work perfectly for mobile devices' touch input. So, bear in mind the following solution is a semi-complete workaround for your problem:
$(document).ready(function(){
var methodToRun = "runMethod(this)"; // Store the value of the onclick attribute of your button.
var condition = false; // Suppose it is enabled at first.
$('#uniqueId').attr('onclick',null);
$('#uniqueId').hover(function(){
// Check your stuff here
condition = !condition; // This will change to both true and false as your hover in and out of the button.
console.log(condition); // Log the condition's value.
if(condition == true){
$('#uniqueId').attr('onclick',methodToRun); // Enable the button's event before the click.
}
},
function(){
console.log('inactive'); // When you stop hovering over the button, it will log this.
$('#uniqueId').attr('onclick',null); // Disable the on click event.
});
});
What this does is it uses the hover event to trigger your checking logic and when the user finally clicks on the button, the button is enabled if the logic was correct, otherwise it does not do anything. Try it live on this fiddle.
P.S.: Convert $ to $j as necessary to adapt this.
P.S.2: Use the Javascript console to check how the fiddle works as it will not change anything on the page by itself.
Your problem is the submit event, just make :
$('form').on('submit', function(e) {
e.preventDefault();
});
and it works. Don't bind the button click, only the submit form. By this way, you prevent to submit the form and the button needs to be type button:
<button type="button" .....>Submit</button>
Assuming there's a form that is submitted when button is clicked.
Try adding
event.cancelBubble();
Hence your code becomes:
$j(document).on('click', '#uniqueId', function(event) {
// Don't propogate the event to the document
if (event.stopPropagation) {
event.stopPropagation(); // W3C model
} else {
event.cancelBubble = true; // IE model
}
if(condition == true) {
// continue...
} else {
return false;
}
return false;
});
Your code is mostly correct but you need to remove J:
$(document).on('click', '#uniqueId', function(event) {...
You also need to remove the onClick event from the inline code - there's no need to have it there when you're assigning it via jQuery.
<button id="uniqueId">Submit</button>
I am writing a function to delete some records. on deletion there is an alert message with 'yes' and 'no' to which user needs to click to delete the record.
The problem is that I want to pass yes to this confirmation without manually clicking on the yes. how can I do this. please provide pointers.
Not saying you should do the following, but here's how one might try to bypass confirmation dialogs.
Replace the confirm function with your own function that returns true.
var realConfirm = window.confirm;
window.confirm = function () { return true; }
deleteRows();
window.confirm = realConfirm;
If you are talking about native javascript's confirm() then, you cannot do what you intend to. If you override the function, you'll not get the popup behaviour.
But if you have a custom alert box kind of thing, then assign an id to the Yes or Ok button.
Then you can do this:
document.getElementById('yesId').click(); //this will trigger a click.
And yes, as Will Newton said, if you don't wanna press the button, just use Return or Enter button.
Hi all I am working in angular js , I want to add confirm message when click delete button
I tried this code :
<a data-ng-click="removeTodo(this)" href="javascript:;"
onclick="javascript:return confirm('Are you sure you want to delete ?')">Delete</a>
This is shown ok and cancel button with the confirm box , if i click the ok button it's going to next process , but if i click the cancel button then it's same as going to same process confirm box was not hide ( The ok button will return true , but same as cancel button will be return true not a false)
But it's working good when i used this below code on click my delete button
$scope.removeTodo = function (Student) {
if (!confirm("Do you want to delete this ? ")) {
return false;
}
//please think , I added Some code for next process in here
};
What is the problem ? what i missed ? Why my first code was not working ?
It is because return false is same as preventing the default action and stopping event propagation - which will prevent the handlers attached to ancestor elements from being executed... but in your case both click handlers are attached to the same element.
So even if the confirm returns false the angular click handler will get executed.
I have no idea if this is even possible, but I thought I would ask since it would be awesome if it is possible.
So basically I have a link with an onclick and in the onclick there are two calls. one to a function and another to _doPostBack.
The first function that is called is a simple function:
function CheckTerms() {
if (!document.Form.agreetoterms.checked) {
alert("Please check the terms and conditions.");
return false;
}
return true;
}
So basically if the check box isnt checked the alert happens and the page doesn't submit. If it is checked it submits. Right now even if it isn't checked, it shows the alert and executes the doPostBack and submits the page. The doPostBack is put into the link dynamically and I don't have access to it, which has made it harder for me. So any ideas or ways to abort it so it doesn't submit?
Thanks!
I'm assuming the _doPostback function handles the posting of the form, and that you don't want the anchor to move the page to the location of its href when clicked. preventDefault does this by preventing the anchor's default action from being taken when clicked.
var a = document.getElementById("yourAnchorId");
a.onclick = function(e){
e.preventDefault();
if (CheckTerms())
_doPostBack();
}
why can't you do the following:
function CheckTerms() {
if (!document.Form.agreetoterms.checked) {
alert("Please check the terms and conditions.");
return false;
}
else{
<<< call you function here >>>
}
return true;
}
The reset action is performed by input type="image" and onclick calls a function called resetForm().
When reset is clicked the form submit should not happen. I tried returning false from resetForm() function and still it doesn't work. Please help me out.
Instead of returning false in resetForm, use preventDefault in the click function:
$('#myButton').click(function(event) {
event.preventDefault(); // yaa!
resetForm();
});
return false does also work, but when jQuery got a function for something, I usually stick with that.
I will make sure that your function is properly returning false, make sure you have no syntax error in your JavaScript.
Good way to test this, try alert("Testing Return!"); right before return false.
If you would like to use return False; as opposed to event.preventDefault();, you must put the return false within the event callback. So, it would need to be like this if you are returning false in resetForm():
$('#myButton').click(function() {
return resetForm();
});
Even simpler, if all you are doing is running a function on click (thanks to JimmyP for that reminder):
$('#myButton').click(resetForm);
In my opinion, it's cleaner, simpler, and involves less typing. All wins for me.
I think everyone else is describing a different way to do what I am suggesting which is:
onClick="return resetForm();"
Otherwise the onClick is calling without caring the return.
There is an actual way of doing it. But it requires a few steps.
Define your ..
You need bind the click even of the input item. use jquery to do it.
write your function
binding:
$(document).ready(function () {
$("#yourinputtypeid").on("click", {Parameter1 : "your parameter value"},
FunctionNameToRun);
}
the Function.
function FunctionNameToRun(event)
{
event.preventDefault();
// the rest of your code
}
That's it. This should prevent the submission / reloading of the page.
I would probably be better to use <input type="reset" /> rather than type="image", because the latter has the semantics of type="submit" and the former seems to have the semantics that you're going for. You could also easily put an image on such a button as well and it would probably save you the trouble of having to write a JavaScript function.
If you want to continue using <input type="image" />, I don't think returning false from the onclick event will do anything. Since it has the semantics of submitting the form, the form will just be submitted. In order to counter that, you could maybe place an onsubmit attribute in the form tag: <form onsubmit="return submitFunction();" />. In the submitFunction you could then check which submit/image button was pressed and depending on that return true or false. Returning false here will prevent the form from submitting.