I click submit button before test time is completed So I show a confirm message "Do you want to really Quit this test" and I click the submit button when Time is completed (Time left is 00:00:00) through javascript, but then also it asks user with confirm message Which I do not want to show on completion of time, How can I achieve this?
This is my button
<asp:Button ID="btnSubmit" class="btn" runat="server"
OnClientClick="return confirm('Do you want to really Quit this test');" Text="Submit Test"
OnClick="btnSubmit_Click" />
This is javascript through which I call Click event when test time is over
<script type="text/javascript">
function
display() {
var hours = document.getElementById('<%=HidH.ClientID %>');
var minutes = document.getElementById('<%=HidM.ClientID %>');
var seconds = document.getElementById('<%=HidS.ClientID %>');
if (hours.value == 0 && minutes.value == 0 && seconds.value == 0) {
alert("Time Given For this Test is Over");
document.getElementById('btnSubmit').click();
}
}
</script>
Instead of binding click event inline call a function where you will prompt user for confirmation and make it option depending on timeout.
Change
OnClientClick="return confirm('Do you want to really Quit this test');"
To
OnClientClick="return myConfirmFun()"
Define myConfirmFun as under.
var showConfirm = false; // defind gloablly
function myConfirmFun()
{
if(showConfirm)
{
showConfirmm = false;
confirm('Do you want to really Quit this test');
}
}
In the display function
if (hours.value == 0 && minutes.value == 0 && seconds.value == 0) {
showConfirm = false;
alert("Time Given For this Test is Over");
}
else
showConfirm = true;
Related
I have button called sales and it have a JavaScript popup when I click on cancel it postback and the values in the form are inserted but when i click on ok it does not post back and the values in the form does not go in the database ( the JavaScript button is actually print call and when button is clicked it asks for print when print dialog box is open it does not post back and data is not inserted in the database)
here is the javascript code
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
__doPostBack();
}
else {
__doPostBack();
}
}
here is the code for button click
<asp:Button ID="btnaddsale" runat="server" Text="Sale" OnClick="btnaddsale_Click" OnClientClick="javascript:confirmAction('printable')"/>
Ok, couple of notes for you:
You want a postback in either case.
Your <asp:Button> will automatically do a postback either way, so you don't need to call __doPoskBack(); in this scenario.
Major issue here is that, if you want a postback, it will happen immediately when the function exits, effectively canceling out the print dialog too soon. To avoid this, we will use a JavaScript trick that will check if the document has focus, and only when it does (when user exits print dialog in the browser) will we return and allow the postback to occur.
To fix the issue,
First: Make the function return true; when user cancels, and wait for focus and then return true if the user wants to print:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
// Check focus after user exits print dialog and then return true for the postback
var document_focus = false;
$(document).focus(function () { document_focus = true; });
setInterval(function () { if (document_focus === true) { return true; } }, 500);
}
else {
return true;
}
}
Then, change the JavaScript code to use the return statement in the OnClientClick event:
<asp:Button ID="btnaddsale" runat="server" Text="Sale"
OnClick="btnaddsale_Click"
OnClientClick="javascript:return confirmAction('printable')"/>
Update based on comments and your changed requirement:
Here's a snippet to make the script pop up after the postback. So you will insert values to database, and then add the print script / confirm dialog on page load using Page.ClientScript.RegisterStartupScript()
Note I don't recommend to embed the script in your C# code, so I'd suggest to take your confirmAction() function and place it (if not already) into a separate "yourScripts.js" file and then just call the function name when the page is loaded using jQuery. Here's an example:
In your master page or page header: This file should contain the confirmAction() function
<script type="text/javascript src="path/to/yourScriptsFile.js">
Then, in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// Only display script on PostBack, not initial page load
if (IsPostBack)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"confirmAction",
#"<script type=""Text/Javascript"">$(document).ready(function() { confirmAction('printable'); });</script>");
}
}
Also note, since you will NOT want a postback now, the confirmAction function should no longer return true; or use the trick code I posted above, and will just return false:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
return false;
}
I have a button, I need to fire an onclick event, and an onclientclick event. The onclientclick would be something like this:
(function($){
$.fn.validate = function() {
var option = $('#<%=LblWarnings.ClientID%>').html();
if (option == "option1_OK" ||
option == "option1_OK")
alert(wrong);
else {
$('#<%=LblWarnings.ClientID%>').html("Incomplete");
alert(wrong);}
};
})(jQuery);
Validating function, checks the text of a label, if condition's true it should go on and execute the OnClick event. And if it's false, it should NOT FIRE the code behind (method called WriteInfo in my .cs file, but just update a label so the user knows something was wrong while he was submitting data.
Is it possible for the onclientclick to stop the onclick event? If so, could you help me providing me the asp:button sentence so I can trigger both events.
Thanks.
After trying Adil Answer, I get an error "object expected"
Maybe there's something wrong the way I'm calling the function?
<asp:Button ID="ButtonRadioValue" CssClass="customButton" runat="server" onclick="WriteInfo" OnClientClick="validate();" Text="Accept" />
You can use stopPropagation() method to stop postback of return false.
Use stopPropagation();
(function($){
$.fn.validate = function(event) {
var option = $('#<%=LblWarnings.ClientID%>').html();
if (option == "option1_OK" ||
option == "option1_OK")
alert(wrong);
event.stopPropagation();
else {
$('#<%=LblWarnings.ClientID%>').html("Incomplete");
alert(wrong);}
};
})(jQuery);
Using return false;
(function($){
$.fn.validate = function() {
var option = $('#<%=LblWarnings.ClientID%>').html();
if (option == "option1_OK" ||
option == "option1_OK")
alert(wrong);
return false;
else {
$('#<%=LblWarnings.ClientID%>').html("Incomplete");
alert(wrong);}
};
})(jQuery);
I am working on a brownfield site that fires asp.net clientside validation, whatever the result it always does a postback. Has anybody any ideas to stop this behavior if it fails the validation?
Thanks in advance.
Podge
You can leverage Custom Validator control w3schools or MSDN link. It allows you to perform client side validation. Usage example.
<asp:CustomValidator id="CustomValidator1" runat="server"
ErrorMessage="Number not divisible by 2!"
ControlToValidate="txtCustomData"
OnServerValidate="ServerValidate"
ClientValidationFunction="CheckEven" /><br>
Input:
<asp:TextBox id="txtCustomData" runat="server" />
<script language="javascript">
<!--
function CheckEven(source, args) {
var val = parseInt(args.Value, 10);
if (isNaN(val)) {
args.IsValid = false;
}
else {
args.IsValid = ((val % 2) == 0);
}
}
// -->
</script>
I was getting the same behavior and fixed it by setting the CausesValidation property to True.
just for example: validate the textbox , if its empty postback not called else postback called.
button click event:
<asp:TextBox id="vTextBox" runat="server" />
<asp:button id="okButton" runat="server OnClick="okButton_Click" OnClientClick=" return isValidate();"/>
<script type="text/javascript">
function isValidate() { var txt = $("#vTextBox").val();
if ( txt === "") { alert("error"); return false; }
else { alert(" no error "); return true; } }
</script>
In my case I had a couple of CustomValidators where the ClientValidationFunction was missing.
Ensure there are no JavaScript errors on the page which could also cause this problem.
For Client Validation you must be calling some JS function for validation:
If you are calling the client side validation method on a button click then you should call it like below:
<asp:Button runat="server" id ="btnSubmit" onClientClick="return ValidateForm();" >
And the Validate Form method should return true or false.
like :
function ValidateForm()
{
/// Validation goes here
if (validated)
{
return true;
}
else{
return false;
}
}
}
Alright my basic question is how do I simulate a button click in javascript.
I know I have to use document.getElementById("btnSubmit").click(); but this doesn't seem to call the onClientClick javascript function as well.
Enviorment:
I am using ASP.NET with C# and javascript.
What happened:
I have an input text area and I want to make sure that users must enter a character before the submit button is enabled. I was able to do this with onkeypress="validateTxt();" which then called this function
function validateTxt() {
var input = document.getElementById("<%=txtUserName.ClientID %>").value;
//Need a min of 3 characters
if(input.length > 1)
{
document.getElementById("btnSubmit").disabled = false;
}
else
{
document.getElementById("btnSubmit").disabled = true;
}
}
The only problem though is doesn't register backspace.
To solve this I found this online
<script type="text/javascript">
document.getElementsByName('txtUserName')[0].onkeydown = function (event) {
if (event === undefined) event = window.event; // fix IE
if (event.keyCode === 8)
validateTxt();
if (event.keyCode === 13) {
document.getElementById("btnSubmit").click();
}
};
Now whenever the user presses the backspace my javascript function is called. This worked great up until I found out that when I press enter from the text area it wouldn't call my javascript function.
Here is all of the relevant code...
<script type="text/javascript">
function InformUser()
{
window.document.getElementById("loadingMessageDIV").style.display = "block";
<%=Page.GetPostBackEventReference(btnSubmit as Control)%>
document.getElementById("btnSubmit").disabled = true;
}
function validateTxt() {
var input = document.getElementById("<%=txtUserName.ClientID %>").value;
//Need a min of 3 characters
if(input.length > 1)
{
document.getElementById("btnSubmit").disabled = false;
}
else
{
document.getElementById("btnSubmit").disabled = true;
}
}
</script>
Here is the text area + javascript bounding function
<asp:TextBox ID="txtUserName" runat="server" Font-Size="11pt" onkeypress="validateTxt();"></asp:TextBox>
<script type="text/javascript">
//We bind the textbox to this function and whenever the backspace key is pressed it will validateTxt
document.getElementsByName('txtUserName')[0].onkeydown = function (event) {
if (event === undefined) event = window.event; // fix IE
if (event.keyCode === 8)
validateTxt();
if (event.keyCode === 13) {
document.getElementById("btnSubmit").click();
}
};
</script>
Here is the submit button
<asp:Button ID="btnSubmit" runat="server" OnClientClick="InformUser();" OnClick="btnSubmit_Click"
Text="Login" Font-Bold="True" Enabled="True" />
<script type="text/javascript">
//Disable the button until we have some actual input
document.getElementById("btnSubmit").disabled = true;
</script>
So to recap it does press the button, but it fails to disable it as well. I even tried to call the InformUser directly when the user presses enter and then press the button, but that didn't work either.
I know it has something to do with how I bound the javascript function to the text area because when I take it out it works.
Thanks for the help
If what you're really trying to do is enable/disable the submit button based on the amount of text in the text area, then it would be simplest just to check the length every time it's changed.
Would you be able to use jQuery? If you can, it's a trivial problem, as jQuery normalises keyboard events so you don't have to worry about different browsers raising different events.
As a simple experiment, I created a jsFiddle with this HTML:
<textarea id="txt"></textarea>
<label id="count" />
and this JavaScript:
$('#txt').keyup(function () {
$('#count').text($('#txt').val().length);
});
On every keyup (I used keyup rather than keydown or keypress as keyup fires after the text has been modified) the length is updated. This registers normal keys, backspace, delete, enter, etc, and works in FF and IE8.
In your case, you'd obviously change the function to enable/disable the submit button.
When Delete button is clicked, the confirmation box should pop up if the selected node has child nodes. Otherwise, it should not do anything.
Right now, when I click on delete, it just deletes without confirming.
Here is the code:
<asp:Button ID="btn_delete" runat="server" Height="32px"
onclick="btn_delete_Click" OnClientClick = "return childnode();"
Text="Delete" Visible="False" />
<script type="text/javascript">
function childnode() {
var treeViewData = window["<%=nav_tree_items.ClientID%>" + "_Data"];
var selectedNode = document.getElementById(treeViewData.selectedNodeID.value);
if (selectedNode.childNodes.length > 0) {
return confirm("heloo");
}
return false;
}
</script>
You'll need to return false from the function if you don't want the button push to go through in some cases. Currently you are only returning a value from the function when calling confirm.
If one or both of the if conditions fail, add a return false if you don't want the event to bubble up activating the button/sending the form.
Modification of your existing code
function childnode() {
var treeViewData = window["<%=nav_tree_items.ClientID%>" + "_Data"];
if (treeViewData.selectedNodeID.value != "") {
var selectedNode = document.getElementById(treeViewData.selectedNodeID.value);
if (selectedNode.childNodes.length > 0) {
return confirm("heloo");
}
return false; // don't send form
}
return false; // don't send form
}
Is it still malfunctioning?
Make sure that the logic inside your function is accurate, webbrowsers will often fail silently when trying to get a property of an undefined variable.
In your definition of your button you have written OnClientClick = "return childnode();", try changing this to OnClientClick="return childnode();" and see if that might solve the problem.
See if the event fires at all, OnClientClick="alert(123);".
Your function have return not in all of it's parts. Probably your function exists without confirm. Review your logic and decide what you want to do if one of your if statements not passed.
Change this:
onclick="btn_delete_Click" OnClientClick = "return childnode();"
To this:
onclick="btn_delete_Click;return childnode();"