OnServerClick event handler not called if using onclick - html

I have a peculiar problem here and I can't by my life figure out what the solution is. Note that the following code is not dynamically created, but just immediately in my aspx file.
<button type="button" runat="server" id="btnSubmit"
OnServerClick="btnSubmit_Click" onclick="return confirm('Sure?');">
Submit
</button>
This works just fine as long as I don't have the onclick attribute there, i.e. the OnServerClick handler is fired as it should. But when I use the onclick attribute it is not, no matter whether I confirm or decline the confirmation dialog box.
What am I doing wrong?

If you look at the source code generated you will see the following:
onclick="return confirm('Sure?'); __doPostBack('btnSubmit','')"
so what is happening is the _doPostBack is never called. The hacky way to do what you're looking for is the following:
<button type="button" runat="server" id="btnSubmit"
OnServerClick="btnSubmit_Click" onclick="if (confirm('Sure?')) ">
The real correct way would be to use a Web Control:
<asp:Button runat="server"
OnClick="btnSubmit_Click" OnClientClick="return confirm('Sure?')" Text="Submit" />

I had more success with
<asp:Button ID="btnSubmit" runat="server" Text="Save" UseSubmitBehaviour="false"
OnClick="btnSubmit_Click" OnClientClick="if (!confirm('Sure?')) return" />

The accepted answer is not perfect. If you do not use type="button", the web page will do postback even you have clicked cancel. The correct and easiest way is to take advantage of short-circuit evaluation and do this hack: replace ; with && !, like below.
<button runat="server" id="btnSubmit"
OnServerClick="btnSubmit_Click" onclick="return confirm('Sure?') && !">
The output will look like this:
<button id="btnSubmit"
onclick="return confirm('Sure?') && ! __doPostBack('btnSubmit','')">
It gives correct return value because true && !undefined will return true and undefined will be evaluated and false && !undefined will return false and undefined will NOT be evaluated which is exactly what we want.

How about chaging button's type to submit, it works well :
<button type="submit" runat="server" id="btnSubmit"
OnServerClick="btnSubmit_Click" onclick="return confirm('Sure?');">
Submit
</button>

Try this:
<button type="button" runat="server" id="btnSubmit"
OnServerClick="btnSubmit_Click" onclick="if(!confirm('Sure?')) return;">
Submit
</button>

It sounds like the onclick event isn't bubbling through.
You should just be able to use
OnClientClick="return confirm('Sure?');
I don't think the other onClick should be necessary.
Edit:
This method would require you to hook your function to the OnClick event manually.
I am making up attributes this morning so in a futile effort to redeem myself-
Another method would be to insert javascript to catch the event. Something like..
$("form").submit(function() {
var resp = confirm("Save & Submit?");
if (resp) {
serializeStats();
return true;
}
else {
return false;
}
});
I do recall there being a better inline way to do this though.
Caffeine time now.

< button> is an HtmlButton control where OnServerClick is the only server-side click event. OnClick is unrecognized by ASP.NET so it gets passed to the client intact in case you want some client-side javascript code to execute before the postback.
< asp:button> is a WebControl which accomplishes the same thing with the OnClick server-side event and OnClientClick for client-side.
I think you're getting the behavior you see because your confirm('sure?') returns false which stops the postback mechanism. That would explain why it works when you don't have onclick in place.

Front Site
<button id="submit1" runat="server"
onclick="if(confirm('Sure?')) { } else{ return false} ;"
onserverclick="submit_ServerClick" >save</button>
Back Site
protected void submit_ServerClick(object sender, EventArgs e)
{
}

Related

Input type="submit" fails to pass its value to the server if the value starts with the capital letter

I have two buttons in my HTML: Save & Save and Exit. On the server I check the value of the button and act accordingly. However if the value of the button starts with a capital letter on the server it is Null. The lower case letter goes through fine.
Below is my code
//HTML:
<input type="submit" class="btn btn-primary btn-block" name="submissionbutton" value="Save" />
<input type="submit" class="btn btn-primary btn-block" name="submissionbutton" value="Save & Exit" />
//SERVER:
var button = Request.Form["submissionbutton"];
model.Save(id, db);
if (button == "Save & Exit")
{
return RedirectToAction("Index");
}
else
{
model = new EditEquipmentViewModel(id, db);
return View(model);
}
If I change the value in the input from "Save" to "save", all works fine but then it displays lower case "save" on the button itself, which is undesirable.
I don't understand how changing the value from Lower Case to Upper Case in the input type="button" nullifies it on the server.
I'll bet the issue is actually your ampersand. If that's the case, look at using encodeURIComponent();
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
"Without encodeURIComponent the ampersand could be interpretted on the
server as the start of a new field and jeopardize the integrity of the
data."
I think the above will sanitize the value you're sending and fix the problem. You could also try a button element instead of an input element. This way your value will be whatever you want versus the text displayed on the button. The other way to do it is make your own button out of a div element. I'm not sure if those suggestions will really help though, as I don't work with asp.net myself.
<button name="name" value="save" type="submit">Save</button>
<button name="name" value="saveexit" type="submit">Save & Exit</button>
I am thinking it has something to do with how Json serializes form values:
Try this link below:
JSON properties now lower case on swap from ASP .Net Core 1.0.0-rc2-final to 1.0.0
Replace this line:
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
With:
jsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();

I made the html & js code to do the validation check. But the data is submitted before checking the data

<form name="mForm" action="${pageContext.request.contextPath}/login/insertSeller.do" method="post">
id : <input type="text" name="id" />
<input type="submit" value="register" onClick="doAction()" />
</form>
<script>
function doAction() {
var f = document.mForm;
var id = f.id;
if (id.value == "") {
alert("insert your id");
id.focus();
return false;
}
return true;
}
</script>
Is there any error to correct?
If I click the button, the alert window opens with a message,
but the data is submitted without the validation check.
What do I need to do?
Please help me :)
You really shouldn’t have inline event handlers in modern HTML. Nevertheless, you could try the following:
<input … onclick="return doAction()">
The return in the onclick causes the input to wait for permission.
For the sake of completeness, here is how I would do it in a modern browser:
First, use a button instead:
<button type="submit">register</button>
Second, give your button a name
<button name="register" type="submit">register</button>
You can give a name to the older style input element, and the process will still work.
Next, add the following to your JavaScript:
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('button[name="register"]).onclick=doAction;
},false);
The main function acts as a startup script. The point of it is that it is waiting for the DOM to have loaded. Otherwise it’s not possible to look for elements that aren’t there yet.
Note that you assign to the onclick event handler the name of the function.

Disable button after form submit

Sounds easy and a well known question, right? I thought so as well. How do I do this in angularJS.
CSHTML
#using (Html.BeginForm("Order", "Shop", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
<div class="container" ng-app="order" ng-controller="orderController">
<button type="submit" ng-disabled="orderButtonClicked" ng-click="orderClicked()" class="btn btn-primary btn-block tf-btn btn-lg">Place Order</button>
</div>
}
AngularJS
angular.module("order", [])
.controller("orderController", ['$scope', '$http','$filter', function ($scope, $http, $filter) {
$scope.orderButtonClicked = false;
$scope.orderClicked = function () {
$scope.orderButtonClicked = true;
}
}]);
As many others reported as well, the form is not submitting when disabling or removing the button. this answer did the same, he claims it is working, but for me is a no go.
You can assume that angular is setup correctly, disabling the button works fine.
I've never had much luck with disabling the submit button in any circumstances - even if it doesn't prevent the form from submitting, the server can get confused because it expects the name/value combination from the submit button.
Instead, I generally hide the submit button, and replace it with something appropriate:
<button type="submit" ng-show="!orderButtonClicked" ng-click="orderClicked()" class="btn btn-primary btn-block tf-btn btn-lg">Place Order</button>
<button ng-show="orderButtonClicked" disabled class="btn btn-primary btn-block tf-btn btn-lg">Place Order</button>
Keep in mind that even in this case, the user may be able to re-submit by hitting enter in a textbox.
Try this way:
<div ng-app="myApp" ng-controller="myCtrl">
<form>
<input type="submit" ng-disabled="orderButtonClicked" ng-click="orderClicked()">
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.orderButtonClicked = false;
$scope.orderClicked = function () {
$scope.orderButtonClicked = true;
}
});
</script>
I will put a break point there and see if orderButtonClicked is set to true when orderClicked() is triggered. Just another thought, I have experience with this issue before when I have an ng-if somewhere inside the controller scope in html. This is because angular seems to create a new scope inside that ng-if dom. The best way to avoid that is to use controllerAs and then access the scope property using controllerName.propertyName.
Does the form submit if you don't disable or remove the button? The angular documentation states that, "For this reason, Angular prevents the default action (form submission to the server) unless the <form> element has an action attribute specified."
So, depending on what you're trying to accomplish, you would have to add javascript in your .orderClicked method to make an ajax call, for example, or whatever you're trying to accomplish.

input tag (type=submit) not working as a link

I tried this html code
<input type="submit" value="Login" class="button" />
It is a part of my html form.
I want to use submit button to submit the data and show ( error.html ) page.
You will wrap it with <form action="error.html"></form>
You can use like this
<html>
<form action="error.html">
<input type="submit" value="Login" class="button"> </input>
</form>
</html>
I am a bit unsure of what you want to do, since you say you already have a form then I guess that the error.html is not calling to the form because you already have another link to the form already. Then this is could be a way to call on two pages almost at the same time. Submit first to the form and then after the sumbit it goes to the linked error page.
Working to call on BOTH the form html and the error.html link:
JavaScript:
<script language="JavaScript">
/** Delay me BEGIN **/
function DelayMyError(){
var count = 0;
// delay in milliseconds
var delay = 100;
var interval = setInterval(function(){
if (count++ < 1) {
window.location.href='error.html';
} else {
clearInterval(interval);
}
}, delay);
}
/** Delay me END **/
</script>
HTML:
<form action="YourFormPage.html">
<input type="button" onclick="form.submit();DelayMyError();" value="Login"></input>
</form>
I hope this was the answer you were searching for. Please contact me back if it worked, I am curious too. Theoretically speaking it should work that it first submits and then after 100 milliseconds it calls for the link called error.html.
How ever if you just want to do a link without a delay you could do it like this, but there is a risk that this more simple approach will not call on the form and that it will only work as a link skipping the submit:
OPTIONAL but I am unsure if this one will call on both the form html and the error.html or not:
<form action="YourFormPage.html">
<input type="button" onclick="form.submit();window.location.href='error.html';" value="Login"></input>
</form>

Image button inside of form, don't want to submit

I have a form with an image button inside of it, and this image button is submitting the form. How do I override this functionality?
<form><input type="image" src="/images/arrow.png" id="imageButton" onClick="javascript:autofill();"/></form>
Why not just have image? return false would also stop the form submit action.
<form><input type="image" src="/images/arrow.png" id="imageButton" onClick="autofill();return false;"/></form>
simply return false after your autofill() function.
onclick="autofill();return false;"
Why use an input element at all? I'd have thought just using an image with an onclick event would be more appropriate if you don't want to cause any submit or reset behaviour
<image src="/images/arrow.png" onclick="javascript:autofill();" width="xxx" height="xxx" alt="Autofill" />
Clicking on button inside a form, submit the form by default. To change it, you have to define a button with type="button". Then, you can add img element inside it. This is the best way I found to do it.
<form>
<button type="button" id="imageButton" onclick="javascript:autofill();">
<img src="images/arrow.png">
</button>
</form>
Try to use event.preventDefault to abort submit event on button click
for example:
$("#idButton").click(function(event) {
if(!valid)
{
//stopEvent
event.preventDefault();
} else {
//submit your form
$("#form").submit();
}
});
Do you want to disable your button after click the submit button/image?
if you're using php you can use the code below or add disabled="disabled" to disable the button as long as you keep it in your input form..
<?php if (isset($disable) && $disable === true) echo ' disabled="disabled"'; ?>
how to add my code
if you use your line of code with an image type:
try:
<form><input type="image" src="/images/arrow.png" id="imageButton" onClick="javascript:autofill();" <?php if (isset($disable) && $disable === true) echo ' disabled="disabled"'; ?> /></form>
Please, read this answer from me (jagb) too if you'd like to use an image without javascript, the needed css can be found on there as well.
Adding attribute type="button" to button tag resolved my issue.