Im struggling getting this to work the way i need. I have two RequiredFieldValidators and two textboxes (Side note: although i have Javascript below i dont mind doing this in another way. I did try code behind but realised validation didnt kick in until i clicked a button twice):
<asp:TextBox ID="EmailTextbox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="EmailR" runat="server" ErrorMessage="Email" ControlToValidate="EmailTextbox" ></asp:RequiredFieldValidator>
<asp:TextBox ID="NameTextbox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="NameR" runat="server" ErrorMessage="Enter your name" ControlToValidate="NameTextbox" ></asp:RequiredFieldValidator>
I then have some script
<script type="text/javascript">
$(document).ready(function () {
$('#<%=EmailTextbox.ClientID%>').keyup(function () {
if ($(this).val() != '') {
ValidatorEnable(document.getElementById('<%= NameR.ClientID%>'), true);
}
else
ValidatorEnable(document.getElementById('<%= NameR.ClientID%>'), false);
});
});
</script>
What im trying to do is:
If EmailTextbox has an email then disable NameTextbox validation.
If EmailTextbox has NO email then enable NameTextbox validation and disable EmailTextbox validation.
With me being pretty new to JQuery/Javascript i have tried several attempts in trying to achieve the above however reading more into it, theres a possibility that i could have the wrong JQuery file (that said with this being an existing project i havent really added any ref to any JQuery so it could well be that i have the code right but need a ref to a JQuery or need to include a new version).
Overall if i can
Thanks
You can try it
$(document).ready(function () {
$('#<%=EmailTextBox.ClientID%>').keyup(function () {
if ($(this).val() != null && $(this).val().length != 0) {
$('#<%= NameRequiredFieldValidator.ClientID%>').hide();
}
else {
$('#<%= NameRequiredFieldValidator.ClientID%>').show();
$('#<%= EmailRequiredFieldValidator.ClientID%>').hide();
}
});
In your code you make the validation enable wrongly when a email
value was not null disable validation on name and enable for email else viceversa
<script type="text/javascript">
$(document).ready(function () {
$('#<%=EmailTextbox.ClientID%>').keyup(function () {
if ($.trim($(this).val()).length)
ValidatorEnable(document.getElementById('<%= NameR.ClientID%>'), false);
ValidatorEnable(document.getElementById('<%= EmailTextbox.ClientID%>'), true);
}
else
{
ValidatorEnable(document.getElementById('<%= NameR.ClientID%>'), true);
ValidatorEnable(document.getElementById('<%= EmailTextbox.ClientID%>'), false);
}
});
});
</script>
You can try this, similar to what you had.
function doSomething()
{
var myVal = document.getElementById('myValidatorClientID');
ValidatorEnable(myVal, false);
}
Or, you could use the visible=true/false on them which renders them inactive (meaning set visible property from code behind).. This might cost you an ajax trip to the code behind using scripmanager and __doPostBack in order to call a server-side function that can than process your logic... A lot of developers don't realize that at least in webforms, you can call your code behind methods from JS, just be very careful - as each call back can get costly...
A good article on communicating from ("front end to code behind via JS") -
http://www.codedigest.com/Articles/ASPNET/320_Doing_or_Raising_Postback_using___doPostBack()_function_from_Javascript_in_AspNet.aspx
Hope that helps or get's you back on the right track!!!
Related
I have this script on a page
<script type="text/javascript">
$(document).ready(function () {
var btnApplyVoucher = document.getElementById('LbtnApplyVoucher');
var voucher = document.getElementById('TxtVoucher');
$("input.voucherCode").bind('keyup paste', function () {
btnApplyVoucher.setAttribute("class", "displayBlack");
});
$("input.voucherCode").bind('blur', function () {
if (voucher.value == '') {
btnApplyVoucher.removeAttribute("class", "displayBlack");
}
});
});
</script>
and I have this textbox which is being manipulated by the above jquery
<asp:UpdatePanel ID="UpdBasket" runat="server">
...
<asp:TextBox ID="TxtVoucher" Text="" runat="server" CssClass="voucherCode" ClientIDMode="Static"/>
...
<asp:LinkButton ID="LbtnUpdateBasket" runat="server" Text="Update Basket" OnClick="LbtnUpdateBasket_Click"/></div>
...
</asp:UpdatePanel>
My problem is when LbtnUpdateBasket is clicked and the update panel updates my jquery stops functioning?! I am not sure what I can do here and nothing I can find on the web is really that helpful to me? I believe my problem is something to do with the .ready() which is running when the page loads but ofcourse this wont run on the update as the whole page doest load, what can i do here?
You need to also fire the jQuery when the update panel updates, as well as when the page loads.
For Example:
<script type="text/javascript">
//Get page request manager
var prm = Sys.WebForms.PageRequestManager.getInstance();
//Add handler for end request (update panel, end update)
prm.add_endRequest(configurePage);
$(document).ready(configurePage);
function configurePage() {
var btnApplyVoucher = document.getElementById('LbtnApplyVoucher');
var voucher = document.getElementById('TxtVoucher');
$("input.voucherCode").bind('keyup paste', function () {
btnApplyVoucher.setAttribute("class", "displayBlack");
});
$("input.voucherCode").bind('blur', function () {
if (voucher.value == '') {
btnApplyVoucher.removeAttribute("class", "displayBlack");
}
});
}
</script>
When you click a button the AJAX request is sent, and then the entire HTML content of the UpdatePanel is re-created based on the results of that request. All of the changes that your JQuery code made will then need to be re-applied. You'll need to ensure that the appropriate code to re-apply those JQuery bindings is run within whatever your link button's click handler is fired.
I am having a user control file without its codebehind file in dotnentnuke.
In which i have put a form in which i have one textbox and one Linkbutton.
I want to pass that textbox's value when i press the button as querystring to access it in another page.
For that i have written following code but it does not work.
<asp:TextBox ID="txtemail" runat="server" class="txtbox" placeholder="Enter Email Here"></asp:TextBox>
<asp:LinkButton ID="LinkButton1" class="lbsubscrb" runat="server"
PostBackUrl="~/Portals/_default/Skins/Gravity/Dummy.aspx?add=<% txtemail.Text %>"
ForeColor="White">SUBSCRIBE</asp:LinkButton>
All answers are appreciated...
It sounds like you really just need your own custom module, instead of trying to take an existing module, without the source code, and make it do something completely different?
That being said, if you really want to take that existing module and make it do that, jQuery is likely going to be your method of choice.
Basically you wan to hijack the click event for the button and send it elsewhere, something along the lines of the following code. I actually wrote most of this last night for another module I was working on (newsletter subscriptions, by the way) but have removed some of my logic to make it simpler for what you are trying to do
EDIT: replaced the txtbox class below to match your textbox's class
<script language="javascript" type="text/javascript">
/*globals jQuery, window, Sys */
(function ($, Sys) {
$(document).ready(function () {
var originalHref = $('.lbsubscrb a').attr('href');
$('.lbsubscrb a').removeAttr("href");
$('.txtbox').focus(function () {
if($('.txtbox').val().indexOf('#')<1)
$('.txtbox').val('');
});
$('.txtbox').bind("keypress", function (e) {
if (e.keyCode == 13) {
$('.lbsubscrb a').click();
}
});
$('.lbsubscrb a').click(function () {
//check if they hit enter in the textbox and submit the form
if (validateEmail($('.txtbox').val())) {
//
//TODO: Add your jquery for the redirect call here.
//
//uncomment this line to actually use the original submit functionality
//eval(originalHref.replace('javascript:', ''));
//if postback is wanted uncomment next line
//$('.lbsubscrb a').removeAttr("href");
} else {
alert('something wrong with your email');
}
});
});
}(jQuery, window.Sys));
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
</script>
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.
How can i get the value that was pressed in the confirm box?
<script type = "text/javascript" language = "javascript">
function confirm_proceed()
{
if (confirm("Are you sure you want to proceed?")==true)
return true;
else
return false;
}
</script>
C#
Button2.Attributes.Add("onclick", "return confirm_proceed();");
Try this, if this is the only button that has this behavior
Button2.Attributes.Add("onclick", "return confirm('Are you sure you want to proceed?')");
it's inline and looks straightforward but if you have multiple controls that behave this way then your original approach would be easy to maintain.
And your original function could be shrunken to
<script type = "text/javascript" language = "javascript">
function confirm_proceed()
{
return confirm("Are you sure you want to proceed?");
}
</script>
You can store the value of confirm_proceed() in an asp:HiddenField
You can modify your script as follows:
<script type = "text/javascript" language = "javascript">
function confirm_proceed()
{
var hiddenField = document.getElementById('hiddenFieldId');
if (confirm("Are you sure you want to proceed?")==true)
{
hiddenField.value = 'true';
return true;
}
else
{
hiddenField.value = 'false';
return false;
}
}
</script>
You can now access first the hidden field's value in your Button2_Click event.
I just face similar problem in a real production project and I solved it by the following:
<asp:Button ID="btn1" runat="server" OnClick="Button1_Click" onClientClick="return confirm('Are you sure you want to proceed?')"/>
so the OnClientClick Client event is raised befoere the onClick which is a server event , so if the user clicks OK then the Client event returns True from the confirm Dialog and therefore the Code Behind this button is executed , on the other hand if the user clicks (Cancel or No) then it would return false and therefore the code behind wont get exected (Server Event is Cancelled)
hope it would help you as I really applied it to my project and worked without any issues.