Disable Submit Button during Postback - javascript

I'm trying to disable the button during form submission but not able to do so. Here is the javascript code
<script type="text/javascript">
function Validate(b)
{
function stuff()
{
var temp = document.getElementById("<%=txt_stuff.ClientID %>").value;
var val = /^[a-zA-Z0-9 ]+$/
if(temp=="")
{
alert("Please Enter Stuff");
return false;
}
else if(val.test(temp))
{
return true;
}
else
{
alert("Name accepts only spaces and charcters");
return false;
}
}
function price()
{
var temp2 = document.getElementById("<%=txt_price.ClientID %>").value;
var val2 = /^[0-9 ]+$/
if(temp2=="")
{
alert("Please Enter Price");
return false;
}
else if(val2.test(temp2))
{
return true;
}
else
{
alert("Price accepts only Number");
return false;
}
}
if(stuff() && price())
{
b.disabled = true;
b.value = 'Submitting...';
return true;
}
else
{
return false;
}
}
</script>
Here is the button code
<asp:Button ID="Button2" runat="server" Text="Add Record" OnClientClick = "return Validate(this)"
onclick="Button2_Click" />
The button gets disabled but the value isn't submitted into the database.
Database update code is
protected void Button2_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(500);
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DTPXP-77A;Initial Catalog=practice;Integrated Security=true";
con.Open();
SqlCommand cmd = new SqlCommand("insert into expense values(#person,#item,#expdate,#price)", con);
cmd.Parameters.Add("#person", SqlDbType.VarChar);
cmd.Parameters.Add("#item", SqlDbType.VarChar);
cmd.Parameters.Add("#expdate", SqlDbType.DateTime);
cmd.Parameters.Add("#price", SqlDbType.Int);
cmd.Parameters["#person"].Value = droplist_person.SelectedItem.ToString();
cmd.Parameters["#item"].Value = txt_stuff.Text;
cmd.Parameters["#expdate"].Value = DateTime.Now.ToString();
cmd.Parameters["#price"].Value = txt_price.Text;
cmd.ExecuteNonQuery();
InsertHistory();
Response.Redirect("Add.aspx");
}

remove the UseSubmitBehavior="false" attribute?
and you dont need to return anithing in the javascript (return false is used to cancel a postback)

I think it's the way you are inserting the items into the database since you said that it disables the button but doesn't insert the database. So to me, that means the event is firing but something is wrong with the way you are inserting. This is how my buttons look, using your code..
protected void Button2_Click(object sender, EventArgs e)
{
string person = droplist_person.SelectedItem.Text;
string item = txt_stuff.Text;
string expdate = DateTime.Now.ToString();
string price = txt_price.Text;
System.Threading.Thread.Sleep(500);
SqlConnection con = new SqlConnection("Data Source=DTPXP-77A;Initial Catalog=practice;Integrated Security=true");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO (expense person, item, expdate, price) VALUES (#person, #item, #expdate, #price)", con);
cmd.Parameters.AddWithValue("#person", person);
cmd.Parameters.AddWithValue("#item", item);
cmd.Parameters.AddWithValue("#expdate", expdate);
cmd.Parameters.AddWithValue("#price", price);
cmd.ExecuteNonQuery();
InsertHistory();
Response.Redirect("Add.aspx");
Button2.Enabled = false; //you can disable the button one the button click as well.
Page.ClientScript.RegisterStartupScript(this.GetType(), "Call my function", "mess();", true);
}
I would also surround that in a try/catch. Also, as far as I know, the Add is the "old" way of inserting items into the database. AddWithValue is going to be the best way since you are inserting items from drop downs and from text boxes. I think this is the where the problem lies. You can also put the connection inside the connection inside the SqlConnection like above to "clean" things up a bit. As to your "2nd" question, I'm not completely sure what you mean, but I hope this solves the problem to your 1st question.
EDIT: Added the disabling of the button since it was described in the title.
EDIT 2: Also, remove the UseSubmitBehavior="false" and the OnClientClick. Instead, you can call the message in the behind code.. Look above for example.
EDIT 3: From what I understand then, you will want to keep what the code the inserts the values. So keep the OnClientClick = "return Validate();" And then in your button click, disable the button. Then you will want to add if(!PostBack) to the page load, like so.. This will enable the button on the page load if the postback has happened. So what will be happening is that you disable the button, then once it posts back, it will be re-enabled.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Button2.Enabled = true;
}
}

Related

Trigger JavaScript Confirm() from code behind

I am working on a Asp.Net application, currently i am trying to trigger a JavaScript Confirm() popup from the code behind. I would like to popup without clicking any button_click event.
IF not blnResult then
popup message with OK& CANCEL
IF OK THEN Exit Sub
ELSE
no display
END IF
I tried to do below things and it's not firing popup, please assist.
1) Created a button in ASPX
<asp:Button ID="btnConfirm" runat="server" Text="Delete-All" OnClick="btnConfirm_Click" OnClientClick="Confirm()"/>
JavaScript function
<script language="javascript" type = "text/javascript">
function Confirm() {
var confirm_value1 = document.createElement("INPUT");
confirm_value1.type = "hidden";
confirm_value1.name = "confirm_value";
if (confirm("Do you want to delete all records?")) {
confirm_value1.value = "Yes";
} else {
confirm_value1.value = "No";
}
document.forms[0].appendChild(confirm_value1);
}
</script>
Code behind,
Public function GetConfirmation()
btnConfirm_Click(btnConfirm, EventArgs.Empty)
End Sub
Above line isn't firing the popup for me.
If I have understood correctly then probably you want to call your code behind click event only when user confirms by click on yes. There are many of ways doing this. I have listed few of them. Choose which ever suits best for you.
Don't know why you have created a hidden input field. What is the purpose of creating it. In case you don't need hidden input filed you can try these out.
Confirmation in HTML Tag
<asp:Button ID="btnConfirm" runat="server" Text="Delete-All" OnClick="btnConfirm_Click" OnClientClick="return confirm('Do you want to delete all records?');"/>
Confirmation in JavaScript
<asp:Button ID="btnConfirm" runat="server" Text="Delete-All" OnClick="btnConfirm_Click" OnClientClick="Confirm();"/>
<script language="javascript" type="text/javascript">
function Confirm() {
return confirm("Do you want to delete all records?");
}
</script>
Or
<script language="javascript" type="text/javascript">
function Confirm() {
var result = confirm("Do you want to delete all records?");
return result;
}
</script>
If you do need to keep hidden input field then use below.
<script language="javascript" type="text/javascript">
function Confirm() {
var confirm_value1 = document.createElement("INPUT");
confirm_value1.type = "hidden";
confirm_value1.name = "confirm_value";
var result = confirm("Do you want to delete all records?");
confirm_value1.value = result ? "Yes" : "No";
document.forms[0].appendChild(confirm_value1);
return result;
}
</script>
Just modify your javascript function.
<script language="javascript" type = "text/javascript">
function Confirm() {
var confirm_value1 = document.createElement("INPUT");
confirm_value1.type = "hidden";
confirm_value1.name = "confirm_value";
if (confirm("Do you want to delete all records?")) {
confirm_value1.value = "Yes";
} else {
confirm_value1.value = "No";
}
document.forms[0].appendChild(confirm_value1);
return false;//this will prevent submit click.
} </script>
just add return statement at last line of function.
return false;
I hope this solution will help you.

Javascript Function Not Firing from C# Function ASP.Net

I am using a asp:Repeater control while trying to develop a screen as shown below:
Submit form
When ToolId is entered on the TextChanged Event I am getting value for MaxToolLife stored as double. When an user enter values greater than the stored value for the field ToolLife I need to show Yes/No popup stating "The value entered is greater than existing value. Do you want to proceed?" on button submit or textchanged event.
Currently I am using the below code but I am not getting Javascript alert.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Convert.ToDouble(txtToolLifeAchieved.Text) > maxToolLife)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "Confirm", "javascript:Confirm();", true);
if (hdnconfirm.Value=="Yes")
{
row["Pcs Produced"] = Convert.ToDouble(txtToolLifeAchieved.Text);
}
else
{
txtToolLifeAchieved.Text = "1";
txtToolLifeAchieved.Focus();
return;
}
}
else
{
row["Pcs Produced"] = Convert.ToDouble(txtToolLifeAchieved.Text);
}
}
In place of Page.ClientScript I have also used "Page.ClientScript.RegisterClientScriptBlock" & /ScriptManager.RegisterStartupScript. Nothing is working as of now. I am unable to call the javascript function from code behind. Any immediate response would help a lot.
The confirm() is as shown below:
function Confirm()
{
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("The data already exists. Do you want to Overwrite data?"))
{
confirm_value.value = "Yes";
document.getElementById('<%= hdnconfirm.ClientID %>').value = "Yes";
}
else
{
confirm_value.value = "No";
document.getElementById('<%= hdnconfirm.ClientID %>').value = "No";
}
document.forms[0].appendChild(confirm_value);
}
So, I will stick to your original code, and this is how your server method should look like:
// This is just to illustrate the limit
private const double MaxToolLife = 100;
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Check the limit first
if (Convert.ToDouble(txtToolLifeAchieved.Text) > MaxToolLife)
{
// If the hidden field is empty show the confirm
// By default the hidden field is empty, it means that user just
// pressed the submit button but not the confirmation dialog
if (string.IsNullOrWhiteSpace(hdnconfirm.Value))
{
ClientScript.RegisterStartupScript(this.GetType(), "Confirm", "Confirm();", true);
return;
}
// If the hidden field is not empty, this postback was made by the confirm
// So check for the value of the hidden field
if (hdnconfirm.Value == "Yes")
{
// Handle 'Yes'
}
else
{
// Handle 'No'
}
}
else
{
// The limit is not reached
}
}
I omitted your specific code above. This is how the form looks like:
<form id="form1" runat="server">
<!-- Hidden field for the confirm result -->
<asp:HiddenField ID="hdnconfirm" runat="server" />
<!-- Text box for user input -->
<asp:TextBox ID="txtToolLifeAchieved" runat="server"></asp:TextBox>
<!-- Submit button -->
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</form>
Than right before the form tag in your page, place your javascript function, it must be place before the form tag, because calling ClientScript.RegisterStartupScript will append the script at the end of your form tag and that time your Confirm() method be defined. And this is your javascript method:
<script type="text/javascript">
function Confirm() {
if (confirm("The data already exists. Do you want to Overwrite data?")) {
document.getElementById('<%= hdnconfirm.ClientID %>').value = "Yes";
}
else {
document.getElementById('<%= hdnconfirm.ClientID %>').value = "No";
}
// Post the form back to server using the '__EVENTTARGET' hidden field
var form = document.getElementById("form1");
// Create hidden field
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "__EVENTTARGET");
input.setAttribute("id", "__EVENTTARGET");
input.setAttribute("value", '<%= btnSubmit.ClientID %>');
// Append input to the form element
form.appendChild(input);
// Submit the form
form.submit();
}
</script>
There is no need to create another hidden field for the confirmation result. Instead just right after the confirm you need to create hidden field with name set to __EVENTTARGET, and the value of that hidden field must be the name of the submit button, and than just call submit method on the form. This will case postback to the server, with the hdnconfirm set to Yes or No while your btnSubmit_Click method will be executed.

how to capture javascript var value into asp.net page

I have an asp.net page on which at a click on Button (btn1), i want to show message box asking user a question "Do you want to overwrite ?" with button "Ok/Overwrite" and "Cancel" , and based on user response , i will have to update my database.
So i was trying to accomplish it using Javascript Confirm function
var r = Confirm('Do you want to overwrite ?)
but now i have to capture this Var r into my page so that i can update my database accordingly
any help how can i do it ?
On this scenario, you don't need to pass in the value of r to the server; you simply don't postback.
Just have something like this:
<asp:button id="btn1" runat="server" OnClientClick="return confirm('Overwrite?');" OnClick="btn1_Click" Text="Submit" />
If the users clicks "OK" then the page will post back and you will update the DB. If the user clicks cancel, the page won't postback at all and you won't have to do anything.
Here is your code:-
Add a hidden field in Net(.aspx) page
<form id="form10" runat="server">
<asp:HiddenField ID="hdnField" runat="server" Value="false" />
</form>
The hidden field should be added under Form Tag.The value of this hidden field is initially "false".
Here is what you need to do in Code Behind file (.cs file)
protected void btnSubmits_Click(object sender, EventArgs e)
{
if (hdnField.Value == "false")
{
AddJavascriptCode(itemValue);
}
else if (hdnField.Value == "true")
{
lblMsg.Text = string.Format("You have entered {0}", itemValue);
hdnField.Value = "false";
}
}
Here is the code to capture the response from OK/Confirm or Cancel button.
private void AddJavascriptCode(string itemValue)
{
string script = #"<script language=""JavaScript"" type=""text/javascript"">
window.onload=function()
{
var IsConfirm = 1;
objField = document.getElementById('" + hdnField.ClientID + #"');
objSubmit = document.getElementById('" + btnSubmit.ClientID + #"');
IsConfirm = newConfirm('Test','You have entered " + itemValue + #" value. Do you want to overwrite ?',1,1,0);
if(IsConfirm == true)
{
objField.value = 'true';
objSubmit.click();
}
else
{
objField.value = 'false';
}
}
function newConfirm(title,mess,icon,defbut,mods)
{
if (document.all)
{
retVal = confirm(mess);
retVal = (retVal==1)
}
else
{
retVal = confirm(mess);
}
return retVal;
}
</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "Test", script);
}
}
Hope this helps you :).

User Control with Client + Server Side CustomValidation; Wrong Client side validator is picked

I have a user control which contains a CustomValidator which is used according to whether a RadioButton is checked or not (there are several RadioButtons, I'm only showing the relevant one)
<asp:RadioButton runat="Server" ID="RadioBetween" GroupName="DateGroup" CssClass="date_group_options_control_radio" />
<asp:TextBox ID="FromDate" runat="server" Columns="8"></asp:TextBox>
<asp:TextBox ID="ToDate" runat="server" Columns="8"></asp:TextBox>
<asp:CustomValidator ID="DateValidator" runat="server" Display="Dynamic" ClientValidationFunction="ValidateDateFields_Client" OnServerValidate="ValidateDateFields"></asp:CustomValidator>
There is some client + server side validation code (the server side code does exactly the same thing and is skipped for brevity)
<script type="text/javascript">
function ValidateDateFields_Client(source, args)
{
if ("<%=EnableValidation%>" == "True")
{
var bRadioBetweenSelected = false;
var oRadio = document.getElementById('<%=RadioBetween.ClientID%>');
if (oRadio != null && (oRadio.checked == true || oRadio["checked"] == true))
{
bRadioBetweenSelected = true;
}
if (bRadioBetweenSelected)
{
var oFromDate = document.getElementById('<%=FromDate.ClientID%>');
var oToDate = document.getElementById('<%=ToDate.ClientID%>');
if (oFromDate != null && oToDate != null)
{
var sFromDate = oFromDate.value;
var sToDate = oToDate.value;
source.innerHTML = ValidateFromToDate(sFromDate, sToDate, args);
if (!args.IsValid)
{
return;
}
}
else
{
args.IsValid = true;
}
}
else
{
args.IsValid = true;
}
}
}
</script>
There are two instances of this control in the page. When running the client side version it hits the wrong one (the version of the control which is disabled). You can see from the generated HTML both are correctly specified. I'm not sure how .NET works out which clientside function to call given they both have the same name.
<script type="text/javascript">
//<![CDATA[
var ctl00_MCPH1_QueryTextValidator = document.all ? document.all["ctl00_MCPH1_QueryTextValidator"] : document.getElementById("ctl00_MCPH1_QueryTextValidator");
ctl00_MCPH1_QueryTextValidator.controltovalidate = "ctl00_MCPH1_SearchTextBox";
ctl00_MCPH1_QueryTextValidator.focusOnError = "t";
ctl00_MCPH1_QueryTextValidator.display = "Dynamic";
ctl00_MCPH1_QueryTextValidator.evaluationfunction = "CustomValidatorEvaluateIsValid";
ctl00_MCPH1_QueryTextValidator.clientvalidationfunction = "ValidateQueryText_Client";
ctl00_MCPH1_QueryTextValidator.validateemptytext = "true";
var ctl00_MCPH1_DisplayOptionsControl1_DateValidator = document.all ? document.all["ctl00_MCPH1_DisplayOptionsControl1_DateValidator"] : document.getElementById("ctl00_MCPH1_DisplayOptionsControl1_DateValidator");
ctl00_MCPH1_DisplayOptionsControl1_DateValidator.display = "Dynamic";
ctl00_MCPH1_DisplayOptionsControl1_DateValidator.evaluationfunction = "CustomValidatorEvaluateIsValid";
ctl00_MCPH1_DisplayOptionsControl1_DateValidator.clientvalidationfunction = "ValidateDateFields_Client";
var ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator = document.all ? document.all["ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator"] : document.getElementById("ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator");
ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator.display = "Dynamic";
ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator.evaluationfunction = "CustomValidatorEvaluateIsValid";
ctl00_MCPH1_PreferencesControl1_PreferencesTabContainer_DisplayOptionsTab_DisplayOptionsControl_DateValidator.clientvalidationfunction = "ValidateDateFields_Client";
//]]>
</script>
Do i need to add something in to scope it? What's the best way to achieve this? If I disable the loading of the second control everything works fine.
Your client validation function is generated with the same name for both your user controls. There will be two ValidateDateFields_Client() functions in your page, and of course the interpreter will only call one of them.
One way to work around that problem would be to generate unique function names:
<script type="text/javascript">
function ValidateDateFields_Client_<%=RadioBetween.ClientID%>(source, args)
{
// ...
}
</script>
<asp:CustomValidator ID="DateValidator" runat="server" Display="Dynamic"
ClientValidationFunction="ValidateDateFields_Client_"
OnServerValidate="ValidateDateFields"></asp:CustomValidator>
protected void Page_PreRender(object sender, EventArgs e)
{
DateValidator.ClientValidationFunction += RadioBetween.ClientID;
}

How to set value to a hidden property with a button?

I have the following files:
view.jsp
<# page import=...
<bean:define id="mForm" name="myForm" type="MyForm"/>
<html:form action="MyFoo" method="post" styleId="myForm" enctype="multipart/form-data">
<html:hidden property="boo"/>
<input type="button" value="Press me" onclick="javascript:changeBoo()"/>
</html:form>
MyForm.java
class MyForm {
private boolean boo;
public void setBoo(boolean boo){
this.boo = boo;
}
public boolean getBoo(){
return this.boo;
}
}
MyFooAction.java
public class MyFooAction extends BaseAction {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward aForward = null;
String forward = "success";
try {
MyForm myForm = (MyForm) form;
String boo = (String)request.getParameter("boo");
if(boo.equals("true")){
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>DONE");
}
else {
//some code here
}
aForward = mapping.findForward(forward);
}
catch (Exception e) {
throw new Exception();
}
return aForward;
}
}
The question is how to implement changeBoo() in Javascript in order to change the value of boo and to invoke MyFooAction with correct value of boo?
First, change your button to type="submit". That will take care of submitting the form for you. Notice how changeBoo() now returns a value for your onclick attribute. This will submit the form if your function returns true.
Also, you'll need to add an id attribute to your hidden field so that you can easily get a reference to it from javascript:
<html:hidden property="boo" id="booId" />
<input type="submit" value="Press me" onclick="return changeBoo();"/>
Then it's just a matter of creating the javascript function:
function changeBoo(){
var boo = document.getElementById('booId');
boo.value = 'The new value';
return true;
}
PS On your <html:form>...</html:form>, make sure you have a way to submit a form. This is usually done by adding <html:submit>.
Now, to come back to your question, your Javascript function will be like this (assuming that your ActionForm name specified on struts-config.xml is "myForm").
fumction changeBoo() {
var boo = document.myForm.boo;
if ("true" == boo.value.toLowerCase() || "yes" == boo.value.toLowerCase() || "1" == boo.value.toLowerCase()) {
boo.value = "false";
} else {
boo.value = "true";
}
}
Bear in mind that Struts converts boolean values to "true" or "false", "yes" or "no", "0" or "1".

Categories

Resources