Prevent from a postback and run OnClick using jQuery - javascript

I'm trying to validate the TextBox and click the Button of asp.net.
<asp:TextBox ID="txtEmail" Placeholder="E-mail" runat="server"></asp:TextBox>
<asp:Button ID="btnLogin" OnClick="btnLogin_Click" runat="server" Text="Login" />
And here is a jQuery code which validate TextBox and then trigger the OnClick method:
var al = document.getElementById('<%=lblAlert.ClientID%>');
var email = document.getElementById('<%=txtEmail.ClientID%>');
var msg = null;
$(document).ready(function () {
$('#<%=btnLogin.ClientID%>').on('click', function (e) {
if (email.innerText == '') {
msg = 'Please! enter email address.';
al.innerText = msg;
}
else {
$('#<%=btnLogin.ClientID%>').click();
}
});
});
Edit:
OnClick method is:
protected void btnLogin_Click(object sender, EventArgs e)
{
// some code
}

You should cancel the click event, when needed, using event.preventDefault().
$(document).ready(function () {
$('#<%=btnLogin.ClientID%>').on('click', function (e) {
if (email.innerText == '') {
msg = 'Please! enter email address.';
al.innerText = msg;
e.preventDefault();
}
});
});
No need to call click again if validation succeeds.

Since in the HTML your button is already clicked when the jquery gets called, your
else {
$('#<%=btnLogin.ClientID%>').click();
}
is redundant.
Here is the thing, if you want to validate and then click, then you should use a different element as a button
If you want to use the same button (recommended) then you have to prevent the postback when the validation fails by returning false.
Simple HTML concepts
<asp:Button ID="btnLogin" OnClick="btnLogin_Click" runat="server" Text="Login" OnClientClick="return false;" />
Will never cause a postback
Here is what I would do
<asp:TextBox ID="txtEmail" Placeholder="E-mail" runat="server"></asp:TextBox>
<asp:Button ID="btnLogin" OnClick="btnLogin_Click" runat="server" Text="Login" OnClientClick="ValidateMe()" />
<script>
var al = document.getElementById('<%=lblAlert.ClientID%>');
var msg = null;
function ValidateMe() {
var email = document.getElementById('<%=txtEmail.ClientID%>');
if (email.innerText == '') {
msg = 'Please! enter email address.';
al.innerText = msg;
return false;
}
else {
return true;
}
}
</script>

Related

Validation for my ASP textboxes is not working using javascript and ASP.NET

I just want to ask why my form validation for my asp textboxes is not working. It should be like when the user does not input a text in the textbox, a description in the paragraph tag will display to please input a text. But it is not working.Please help me on solving this.
Here is the javascript code:
function checkForm() {
var errors = [];
if ($("#itemBrand").value == "") {
errors[0] = "Please input a text!";
}
if ($("#itemModel").value == "") {
errors[1] = "Please input a text!";
}
if (errors.length > 0) {
if (errors[0] != null) {
document.getElementById("itemBrandValidate").innerHTML = errors[0];
}
if (errors[1] != null) {
document.getElementById("itemModelValidate").innerHTML = errors[1];
}
return false;
}
return true;
}
And here is the aspx:
<asp:TextBox ID="itemBrand" runat="server" BackColor="#FFFF66"
BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px">
</asp:TextBox><br />
<p id="itemBrandValidate"></p>
<asp:TextBox ID="itemModel" runat="server" BackColor="#FFFF66"
BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px">
</asp:TextBox><br />
<p id="itemModelValidate"></p>
<asp:Button ID="Button1" runat="server" CssClass="submitButton" Text="Save
Item" OnClick="Button1_Click" OnClientClick="return checkForm()"/>
Add ClientIdMode = "Static" on your textboxes. Otherwise the .NET platform generates an Id which is not the same as the server ID property and your Jquery selector is not working as expected.
For example:
<asp:TextBox ID="itemBrand" ClientIDMode="static" runat="server" BackColor="#FFFF66"
BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px">
</asp:TextBox>
Client side id of asp.net server controls is different from server side id.
You may use ClientIDMode = "Static" (introduced in .NET 4.0) or you might use ClientID as shown below , also I've tried to re-write your validation function a bit.
function checkForm() {
var success = true;
var itemBrandID = "<%= itemBrand.ClientID %>" ;
if ($("#" + itemBrandID).value == "") {
success = false;
document.getElementById("<%= itemBrandValidate.ClientID %>").innerHTML = "Please input a text!";
}
var itemModelID = "<%= itemModel.ClientID %>" ;
if ($("#" + itemModelID).value == "") {
success = false;
document.getElementById("<%= itemModelValidate.ClientID %>").innerHTML = "Please input a text!";
}
return success;
}
Also suggest you to read this excellent post by Rick Strahl on A generic way to find ASP.NET ClientIDs with jQuery
Hope this helps !

Disable submit button if two textboxes have no value not working properly

I have two text-boxes and one button. I want that the button be disabled if one of the textboxes have no value. With this code the button is enabled if just one textbox has a value.
HTML
<asp:TextBox ID="TextBox2" runat="server" onblur = "Toggle()"></asp:TextBox>
<asp:TextBox ID="TextBox1" runat="server" onblur = "Toggle()"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" Enabled = "false" />
JavaScript
function Toggle() {
var txt1 = document.getElementById("<%=TextBox1.ClientID %>");
var txt2 = document.getElementById("<%=TextBox2.ClientID %>");
var btn = document.getElementById("<%=Button1.ClientID %>");
if (txt1.value == "" && txt2.value == "") {
btn.disabled = true;
} else {
btn.disabled = false;
}
}
Try
if (txt1.value && txt2.value) btn.disabled = false;
else btn.disabled = true;

Cancel ajax modalpopupextender using javascript

I have a modalpopupextender with a targetcontrolid = buttCopyFormula. The buttCopyFormula is wrapped in a span tag for the user to verify they want to proceed. The button also has a javascript function that verifies there is text in one of the fields and if there is places it in a textbox within the modalpopup.
If there isn't text in the field I want to cancel the popup and display a message.
I've had the span around the button for a while, but am just adding the verification function. I would imagine there is a better way to do this, but just not sure what it is.
What is the best way to execute this functionality?
TargetControl Button
<span onclick="return confirm('Copy the selected formula?')">
<asp:ImageButton ID="buttCopyFormula" ImageAlign="AbsBottom" OnClientClick="transferName()" runat="server" ImageUrl="~/images2020/copy_32.png" />
<b style="color:White">Copy</b>
</span>
Modal Popup
<asp:ModalPopupExtender ID="ModalPopupExtender2" Y="20" runat="server"
BackgroundCssClass="modalBackground" CancelControlID="buttFormulaCancel"
PopupControlID="Panel2" TargetControlID="buttCopyFormula">
</asp:ModalPopupExtender>
<asp:Panel ID="Panel2" runat="server" CssClass="modalQuestionBackground"
Style="display:none"><br />
<h5>Enter a Name for the Formula</h5>
<br /><br />
Formula Name:
<asp:TextBox ID="txtFormulaNameNew" CssClass="controltext" Width="65%" runat="server" Text=""></asp:TextBox><br /><br />
<center>
<asp:Button ID="buttFormulaSaveNew" runat="server" CssClass="button"
OnClick="buttFormulaSaveNew_Click" Text="Save Formula" />
<asp:Button ID="buttFormulaCancel" runat="server" CssClass="button"
Text="Cancel" />
</center>
<br />
</asp:Panel>
JavaScript Function
function transferName() {
var v = document.getElementById("ctl00_ContentPlaceHolder1_txtFormulaNameNew").value;
var f = document.getElementById("ctl00_ContentPlaceHolder1_txtFormulaName");
if (v === "") {
alert("Please select the formula you want to copy before proceeding");
return false;
}
f.value = v
}
I've been working on this and first removed the span around the button, put a fake hyperlink for the modal popup and added a behavior id to the popup. I have also changed the javascript as follows...
New Javascript
function transferName() {
var v = document.getElementById("ctl00_ContentPlaceHolder1_txtFormulaNameNew").value;
var f = document.getElementById("ctl00_ContentPlaceHolder1_txtFormulaName");
if (f === "") {
alert("Please select the formula you want to copy before proceeding");
return false;
} else {
if (confirm('Copy selected formula?')) {
f.value = v;
var mod = $find("ModalPopupExtender2");
alert(mod.id.toString);
mod.show;
return false;}
}
}
I still can't get the modalpopup to show. I imagine it's because it's wrapped in an update panel. Any ideas??
You may subscribe to showing event of ModelPopupExtender and cancel showing dependent on some conditions. Put script below at page AFTER THE ScriptManager control
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
function pageLoadedHandler(sender, args){
var popupExtender = $find("ModalPopupExtender2"); // BehaviorId of popup extender
popupExtender.remove_showing(onPopupShowing);
popupExtender.add_showing(onPopupShowing);
}
function onPopupShowing(sender, args) {
var txtFormulaNameNew;
var txtFormulaName = $get("<%= txtFormulaName.ClientID %>");
if (formulaTextBox.value.length === 0) {
alert("Please select the formula you want to copy before proceeding");
args.set_cancel(true);
} else {
if (confirm('Copy selected formula?')) {
txtFormulaNameNew = $get("<%= txtFormulaNameNew.ClientID %>");
txtFormulaNameNew.value = txtFormulaName.value;
}
}
}

ASP.NET Password and Confirmation in ClientSideEvents

I have 2 ASPxTextBox, ASPxValidationSummary and ASPxButton
In JS file there is OnPasswordValidation function
But when i type a password then click Tab button the SetIsValid(false)
on txt_password control doesn't work but it work on txt_ConfirmPassword
Why ?
<dx:ASPxTextBox ID="txt_password" runat="server" Password="true" AssociatedControlID="txt_password">
<ClientSideEvents Validation="OnPasswordValidation" />
</dx:ASPxTextBox>
<dx:ASPxTextBox ID="txt_ConfirmPassword" runat="server" Password="true" AssociatedControlID="txt_ConfirmPassword">
<ClientSideEvents Validation="OnPasswordValidation" />
</dx:ASPxTextBox>
<dx:ASPxButton ID="btnSubmit" runat="server" Text="Submit" ClientInstanceName="btnSubmit" onclick="btnSubmit_Click" AutoPostBack="False">
<ClientSideEvents Click="function(s, e) {onClickBtnSubmit();}"/>
</dx:ASPxButton>
function OnPasswordValidation(s, e) {
var objpassword = GetObj('txt_password');
var objConfirmPassword = GetObj('txt_ConfirmPassword');
var password = aspxGetControlCollection().Get(objpassword.id);
var ConfirmPassword = aspxGetControlCollection().Get(objConfirmPassword.id);
if (password.GetValue() == null) {
password.SetIsValid(false);
ConfirmPassword.SetIsValid(false);
return;
}
if (ConfirmPassword.GetValue() == null) {
password.SetIsValid(false);
ConfirmPassword.SetIsValid(false);
return;
}
if (password.GetValue().length > 5 || ConfirmPassword.GetValue().length > 5) {
if (password.GetValue() == ConfirmPassword.GetValue()) {
password.SetIsValid(true);
ConfirmPassword.SetIsValid(true);
}
else {
password.SetIsValid(false);
ConfirmPassword.SetIsValid(false);
password.SetErrorText = "Password must equal with Confirm Password";
ConfirmPassword.SetErrorText = "Password must equal with Confirm Password";
}
}
else {
ConfirmPassword.SetIsValid(false);
password.SetIsValid(false);
}
}
This is not a proper way to implement validation. This way OnPasswordValidation function is executed twice, once for every textbox.
Here is a ticket with sample project that should do what you need:
http://www.devexpress.com/Support/Center/p/Q233058.aspx
I advice you to read DevExpress controls validation overview in order to understand how to implement validation on devex controls.

JavaScript - return false from function is not working?

I m calling a javascript function on asp.net button client click and want to prevent post back. function works but it do not stop to be posted back. My Javascript is:
function User2Check()
{
var user2id=document .getElementById("txtP2UserName");
var user2password=document .getElementById("txtP2Password");
if(user2id.value=='' & user2password.value!='')
{
alert("User name is required");
user2id=document .getElementById("txtP2UserName").foucs();
e.preventDefault();
return false;
}
if(user2id.value!='' & user2password.value=='')
{
alert("Password is required");
user2id=document .getElementById("txtP2UserPassword").foucs();
e.preventDefault();
return false;
}
}
The I am calling this function is:
<asp:Button runat="server" ID="btnSubmit" OnClientClick="return User2Check();" TabIndex="12" Text="Submit" onclick="btnSubmit_Click" />
plz guide.
Your javascript takes a parameter but the call from the button's OnClientClick has no parameter. I would think since e is null, the function terminates or returns before returning false but since focus() calls are before calling anything on e, the function seems to be working.
you should use && instead of &
if(user2id.value!='' && user2password.value=='')
AND : Function needs an argument, but you are calling with no argument
You can do it as
function User2Check(e)
{
var user2id=document .getElementById("txtP2UserName");
var user2password=document .getElementById("txtP2Password");
if(user2id.value=='')
{
alert("User name is required");
user2id=document .getElementById("txtP2UserName").focus();
e.preventDefault();
return false;
}
if(user2password.value=='')
{
alert("Password is required");
user2id=document .getElementById("txtP2UserPassword").focus();
e.preventDefault();
return false;
}
return true;
}
<asp:Button runat="server" ID="btnSubmit" OnClientClick="return User2Check(event);" TabIndex="12" Text="Submit" onclick="btnSubmit_Click" />
You use below code and remove " e.preventDefault();" from code.
function User2Check()
{
var user2id=document .getElementById("txtP2UserName");
var user2password=document .getElementById("txtP2Password");
if(user2id.value=='')
{
alert("User name is required");
user2id=document .getElementById("txtP2UserName").focus();
return false;
}
if(user2password.value=='')
{
alert("Password is required");
user2id=document .getElementById("txtP2UserPassword").focus();
return false;
}
return true;
}
and in server side code
use
<asp:Button runat="server" ID="btnSubmit" OnClientClick="return User2Check();" TabIndex="12" Text="Submit" onclick="btnSubmit_Click" />
You've misspelled foucs();
The code will stop running after that error.
Since you don't appear to be returning true, put an exclamation mark before the function. For example:
!function(){
// Code here!
}

Categories

Resources