I'm making a simple remove link with an onClick event that brings up a confirm dialog. I want to confirm that the user wants to delete an entry. However, it seems that when Cancel is clicked in the dialog, the default action (i.e. the href link) is still taking place, so the entry still gets deleted. Not sure what I'm doing wrong here... Any input would be much appreciated.
EDIT: Actually, the way the code is now, the page doesn't even make the function call... so, no dialog comes up at all. I did have the onClick code as:
onClick="confirm('Delete entry?')"
which did bring up a dialog, but was still going to the link on Cancel.
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt_rt"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<script type="text/javascript">
function delete() {
return confirm('Delete entry?')
}
</script>
...
<tr>
<c:if test="${userIDRO}">
<td>
<a href="showSkill.htm?row=<c:out value="${skill.employeeSkillId}"/>" />
<img src="images/edit.GIF" ALT="Edit this skill." border="1"/></a>
</td>
<td>
<a href="showSkill.htm?row=<c:out value="${skill.employeeSkillId}&remove=1"/>" onClick="return delete()"/>
<img src="images/remove.GIF" ALT="Remove this skill." border="1"/></a>
</td>
</c:if>
</tr>
There's a typo in your code (the tag a is closed too early).
You can either use:
<img ...>
note the return (confirm): the value returned by scripts in intrinsic evens decides whether the default browser action is run or not; in case you need to run a big piece of code you can of course call another function:
<script type="text/javascript">
function confirm_delete() {
return confirm('are you sure?');
}
</script>
...
<img ...>
(note that delete is a keyword)
For completeness: modern browsers also support DOM events, allowing you to register more than one handler for the same event on each object, access the details of the event, stop the propagation and much more; see DOM Events.
Well, I used to have the same problem and the problem got solved by adding the word "return" before confirm:
onclick="return confirm('Delete entry?')"
I wish this could be heplful for you..
Good Luck!
I use this, works like a charm. No need to have any functions, just inline with your link(s)
onclick="javascript:return confirm('Are you sure you want to delete this comment?')"
I had issue alike (click on button, but after cancel clicked it still removes my object), so made this in such way, hope it helps someone in the future:
$('.deleteObject').click(function () {
var url = this.href;
var confirmText = "Are you sure you want to delete this object?";
if(confirm(confirmText)) {
$.ajax({
type:"POST",
url:url,
success:function () {
// Here goes something...
},
});
}
return false;
});
Using a simple link for an action such as removing a record looks dangerous to me : what if a crawler is trying to index your pages ?
It will ignore any javascript and follow every link, probably not a good thing.
You'd better use a form with method="POST".
And then you will have an event "OnSubmit" to do exactly what you want...
First of all, delete is a reserved word in javascript, I'm surprised this even executes for you (When I test it in Firefox, I get a syntax error)
Secondly, your HTML looks weird - is there a reason you're closing the opening anchor tags with /> instead of just > ?
<img src="images/delete.png" onclick="return confirm_delete('Are you sure?')">
<script type="text/javascript">
function confirm_delete(question) {
if(confirm(question)){
alert("Action to delete");
}else{
return false;
}
}
</script>
If you want to use small inline commands in the onclick tag you could go with something like this.
<button id="" class="delete" onclick="javascript:if(confirm('Are you sure you want to delete this entry?')){jQuery(this).parent().remove(); return false;}" type="button">
Delete
</button>
try this:
OnClientClick='return (confirm("Are you sure you want to delete this comment?"));'
I've had issue with IE7 and returning false before.
Check my answer here to another problem: Javascript not running on IE
Related
The following code does not redirect to the given webpage
<form>
<button onclick='window.location.replace("../magnet/index.php")'>Replace document</button>
</form>
It is so because when you create a button within the form tags, it is created as a submit button by default. So, instead of redirecting the webpage, it submits the data and reloads the current webpage.
The following code will do the required job because now, the type of the button is button and not submit.
<button type="button" onclick='window.location.replace("../magnet/index.php")'>Replace document</button>
Even better, you can place your redirect code into a JavaScript function. Then you can call that function from within your HTML code. Like this
<script type="text/javascript">
<!--
function redirectTo(sUrl) {
window.location = sUrl
}
//-->
</script>
<button onclick="redirectTo('../magnet/index.php')">Get HTML!</button>
Hope this will work for you. Cheers
The answer was to add type="button" like #shivamag00 explained.
But be careful with replace(), it's not possible to use "back" to navigate back to the original document since you are replacing the history state.
An alternative is to use the assign() function, (documentation here)
Suppose you have a base url as
www.website.come
and want to go to
www.website.come/new-page
it's simple
<button type="button" onclick='window.location.assign("new-page")'>Go to new page</button>
It's worked for me, hope it's useful for someone else.
I have following html+ js code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
foo
</body>
<script type="text/javascript">
function func(k){
alert(1);
return false;
}
</script>
</html>
Can you explain how to refactor following code that after click on href code func executes but # doesn't add to the URL and page shouldn't be reload?
Use javascript:void(0); instead of # as follows:
foo
Using the void operator in the href attribute of the anchor tag ensures that the browser will still display it the same way as any other anchor tag (depending on your CSS settings, this is generally a blue underlined text that changes the cursor when hovered over... etc), prevents the page redirecting to a URL that's just effectively the same page but with the added hash character (#) at the end of the address line, while also makes your onclick event to fire.
You can simply remove the href attribute:
<a id='key' onclick="func(0)">foo</a>
Change it to:
vvvvvvv
foo
To be more semantically correct I would be using a button with the following onclick:
<button id=key onclick="return func(0)">foo</button>
This way there is no need to hack around with e.preventDefault / return false.
I think you forgot the quotation marks in "key"
foo
Inside func, you could do:
func(event){ event.preventDefault(); /* More code here! */ }
preventDefault will prevent redirection, after that line, you could add any logic you want.
However, if you don't want a redirect, it is recommended to use a button instead of an a
If we want to stop redirect. We have have to return false.So we can do like that:
html:
<a onclick="return check()" href="{% url 'app_name:delete_url' item.id %}" title='Delete Item' class="btn btn-sm btn-outline-success mr-1"
<i class="fa fa-trash"></i></a>
script:
function check(){
if (confirm("Do you want to delete?") == true) {
return true;
} else {
//cancle
return false
}
}
I have a simple enough problem: I have an ASP.NET control button and I want to make it fade out and then call some function (such as an alert) using JQuery. Here is what I have so far:
ASP Code for the Button:
<div id="begin">
<span id="startButtonSpan">
<asp:Button ID="startButton" class="startButton" runat="server" Text="Click Me!" OnClientClick="startButtonClick()"/>
</span>
</div>
JavaScript:
function startButtonClick()
{
$("#startButtonSpan > input").fadeOut(500, callAlert());
}
function callAlert()
{
alert("Made it here...");
}
When I click the button, the alert displays but the page does not even seem to try to perform the fadeOut. When I close the alert, the button is still there, staring at me.
Can anyone see any mistakes or does anyone have any suggestions on how I might be able to achieve the intended goal of fading out my button? Fadeout is really just my way of testing whether I can manipulate ASP controls using jQuery, so more than just the simple fadeOut, this is me trying to learn how to do that.
I tried a slightly more simple jQuery call using the code below, but it does not seem to work either:
ASP Portion:
<div id="begin">
<span id="startButtonSpan">
<asp:Button ID="startButton" class="startButton" runat="server" Text="Click Me!" OnClientClick="startButtonClick()"/>
</span>
</div>
<div id="jQueryTest" style="display:none;">
Block for testing jQuery.
<h1 id="testMessage">Child element for the ASP div.</h1>
</div>
Javascript Portion:
function startButtonClick()
{
$("#jQueryTest").css("display", "block");
$("#jQueryTest").show();
}
For this example, the text does display, but it immediately disappears again.
Any help or suggestions as to what I might be doing wrong would be greatly appreciated.
Use the class as a selector $('.startButton') instead of the ID since ASP.Net controls change their IDs dynamically when rendered by appending its Page & Control information.
$(".startButton").fadeOut(500, callAlert);
Or, if you're adamant about using the ID, here is another way to handling the selector,
$("#<%=startButton.ClientID %>")
Or, as Jacob suggested in his answer, you could ClientIDMode="Static", but this works only if your application is .Net 4.0 or above.
Also, use CssClass instead of class
<asp:Button ID="startButton" Csslass="startButton" runat="server" Text="Click Me!" />
The first example has 2 problems.
1. You should write
$("#startButton").fadeOut(500, callAlert);
and not
$("#startButton").fadeOut(500, callAlert());
2. For ASP.NET you must set ClientIDMode="Static" ortherwise asp.net will alter your id.
<asp:Button ID="startButton" ClientIDMode="Static" ... OnClientClick="startButtonClick()"/>
How about the fact that your code is fine (although other answers here should be considered) but your button is making a post back to the server and simply your browser does not have enough time to render the fade effect.
To test this, add a return false; to the OnClientClick property. This will of course cancel your action on the server but you will obtain the fade effect:
<asp: Button ... OnClientClick="startButtonClick();return false;"></asp:Button>
To work around this and still submit your request, you can try to use the ASP.NET __doPostBack method in JavaScript
ASP.NET:
<asp:Button ID="startButton" class="startButton" runat="server" Text="Click Me!" OnClientClick="startButtonClick(this);return false;"/>
JavaScript:
function startButtonClick(button)
{
$("#startButtonSpan > input").fadeOut(500, function(){__doPostBack(button.name, "")});
}
The __doPostBack method takes two arguments: the name of the control that is doing the postback and a postback argument that can be use to send more info on the server. In the case of the asp:Button, the name of the button should be sufficient to send the request without a problem.
Using this technique you will fade the button on the client and also trigger the action on the server. I cannot guarantee that this exact code will work (I don't have access to a dev environment right now) but you should get the idea.
If I could, I would like to provide another answer for those that use MasterPages and find that you can't always use $("#<%= SomeContentControl.ClientID %>") when working with Content controls.
What I do is set the MasterPage ID in my Init() like this:
protected void Page_Init( object sender, EventArgs e )
{
// this must be done in Page_Init or the controls
// will still use "ctl00_xxx", instead of "Mstr_xxx"
this.ID = "Mstr";
}
Then, you can do something like this with your jQuery:
var masterId = "Mstr",
$startButton = getContentControl("startButton"),
$message = $("#jQueryTest");
function getContentControl( ctrlId )
{
return $("#" + masterId + "_" + ctrlId);
}
function hideStartButton()
{
$startButton
.stop(true, true)
.fadeOut("slow", showMessage);
}
function showMessage()
{
$message
.stop(true, true)
.fadeIn("slow");
}
$startButton.on("click", hideStartButton);
Here is a jsFiddle that has the Mstr_ prefix already inserted as if ASP.NET rendered it.
I am using ASP.NET MVC 3 with the Yahoo API version 3. I am trying to get my YUI3 button to redirect to another page when I click on it, this button is my cancel button. The cancel button is a plain button type, but it is being treated like a submit button. It is not redirecting to the correct page, but acting like a submit button and it kicks off my page validation like what the submit button would do.
I thought that it might be with my HTML but I did validate it. It validated 100% correct. So I then stripped down the whole page to a bare minimum but the cancel button is still working like a submit button. Here is my HTML markup:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Create2</title>
</head>
<body class="yui3-skin-sam">
<h1>Test submit</h1>
#using (Html.BeginForm())
{
<button id="SaveButton" type="submit">Save</button>
<button id="CancelButton" type="button">Cancel</button>
}
<script src="http://yui.yahooapis.com/3.6.0pr4/build/yui/yui-min.js"></script>
<script>
YUI().use('button', function (Y) {
var saveButton = new Y.Button({
srcNode: '#SaveButton'
}).render();
var cancelButton = new Y.Button({
srcNode: '#CancelButton',
on: {
'click': function (e) {
Y.config.win.location = '/Administration/Department/List';
}
}
}).render();
});
</script>
</body>
</html>
I'm not sure what I am doing wrong here? Is this maybe a bug in their API? I am testing on IE8 and on the latest version of FireFox.
UPDATE:
I forgot to mention that if these buttons are not between form tags then the redirect works fine. If I put them in form tags then the redirect does not work.
I would use a link because you are redirecting to another page. Doing it this way you wouldn't need to initialize it with javascript or register the onClick listener.
<button id="SaveButton" type="submit">Save</button>
<a id="CancelButton" href='/Administration/Department/List'>Cancel</a>
Look at this link to style your link: http://yuilibrary.com/yui/docs/button/cssbutton.html
The Y.Button widget is removing the type attribute from the Cancel button. This makes that button behave like a submit button.
There are many possible paths to make this work. I'll start from simple to complex. The first is to avoid the issue entirely and not use JavaScript at all. Just use a link:
<form action="/Administration/Department/Create2" method="post">
<button class="yui3-button">Save</button>
<a class="yui3-button" href="/Administration/Department/List">Cancel</a>
</form>
After all, all that the Button widget is doing is adding a couple of css classes to each tag and a lot of other stuff that makes more complex widgets possible. As you can see in the Styling elements with cssbutton example, even <a> tags can look like nice buttons using just the YUI css styles. If you don't have to use JavaScript, better not to use it.
A second option is to avoid the Y.Button widget and use the Y.Plugin.Button plugin. It's more lightweight in both kb and processing power. And it doesn't touch the tag attributes, so your location code will work.
YUI().use('button-plugin', function (Y) {
Y.all('button').plug(Y.Plugin.Button);
Y.one('#CancelButton').on('click', function () {
Y.config.win.location = '/Administration/Department/List';
});
});
And finally you can hack around the behavior of the Y.Button widget by preventing the default action of the button:
var cancelButton = new Y.Button({
srcNode: '#CancelButton',
on: {
'click': function (e) {
e.preventDefault();
Y.config.win.location = '/Administration/Department/List';
}
}
}).render();
How do I make one of those hyperlinks where when you click it, it will display a popup asking "are you sure?"
<INPUT TYPE="Button" NAME="confirm" VALUE="???" onClick="message()">
I already have a message() function working. I just need to know what the input type for a hyperlink would be.
<a href="http://somewhere_else" onclick="return confirm()">
When the user clicks the link, the confirm function will be called. If the confirm function returns false, the link traversal is cancelled, if true is returned, the link is traversed.
try to click, I dare you
with the function
function confirmAction(){
var confirmed = confirm("Are you sure? This will remove this entry forever.");
return confirmed;
}
(you can also return the confirm right away, I separated it for the sake of readability)
Tested in FF, Chrome and IE
As Nahom said, except I would put the javascript:message() call directly in the href part (no need for onclik then).
Note: leaving the JavaScript call in the onClick has a benefit: in the href attribute, you can put a URL to go to if the user doesn't have JavaScript enabled. That way, if they do have JS, your code gets run. If they don't, they go somewhere where they are instructed to enable it (perhaps).
Now, your message routine must not only ask the question, but also use the answer: if positive, it must call submit() on the form to post the form. You can pass this in the call to ease the fetching of the form.
Personally, I would go for a button (input tag as you show) instead of a simple link to do the process: it would use a more familiar paradigm for the users.
[EDIT] Since I prefer to verify answers I give, I wrote a simple test:
<script type="text/javascript" language="JavaScript">
function AskAndSubmit(t)
{
var answer = confirm("Are you sure you want to do this?");
if (answer)
{
t.form.submit();
}
}
</script>
<form action="Tests/Test.html" method="GET" name="subscriberAddForm">
<input type="hidden" name="locationId" value="2721"/>
<input type="text" name="text" value="3.1415926535897732384"/>
<input type="button" name="Confirm" value="Submit this form" onclick="AskAndSubmit(this)"/>
</form>
Yes, the submit just reload the page here... Tested only in FF3.
[EDIT] Followed suggestion in the comments... :-)
???
This answer would be OK only when the click need NOT navigate the user to another page.