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.
Related
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!!!
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;
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 creating some text boxes at runtime and I would like to change the color of the text box if the text box has been left blank
and the user submits the form.
I am using the code behind approach, this is the code I wrote in the .aspx.cs file
textBoxObj is the text box object that I create at runtime and it is the object on which I want the empty validation.
CustomValidator customValidatorObj = new CustomValidator();
customValidatorObj.ControlToValidate = textBoxObj.ID;
customValidatorObj.ClientValidationFunction = "changeColorofTextBox";
and I wrote a small Javascript snippet within the .aspx file which goes as follows (I haven't yet written the logic to change the color,
just making it not valid for now)
<script type="text/javascript">
function changeColorofTextBox(oSrc, args) {
if (args.Value.length > 0) {
args.IsValid = true;
}
else {
args.IsValid = false;
}
}
</script>
In the submit button click function of the form, I have this check if(Page.IsValid), then submit the form. However, even when the text box is empty,
the form gets submitted. It seems like the function is not even being hit. Do you have any pointers on what I am doing wrong?
I am fine with either client side or server side validation, whichever works.
EDIT
I got the error, I just had to do this
customValidatorObj.ValidateEmptyText = true;
and it started working.. Thank you, I didn't realize that the customValidator class does not try validating if the control is blank.
But I am stuck again :(
In the form, I have many text boxes. Suppose, the user entered text for 3 of the text boxes and left 2 of them blank, how do I find the text box ids so that I can change the color of only the blank ones. or, how can I write code in the javascript to find out the control ID at runtime?
I know we have to do this
document.getElementById(CONTROLIDGOESHERE).style.backgroundColor = "red";
but how I get the CONTROLIDGOESHERE value to pass to the getElementById function?
Any pointers, thanks.
Try setting customValidatorObj.EnableClientScipt = True
Assuming you are running .NET Framework version 4.0 then you could declare your textboxes using ClientIDMode="Static". That way they'll have the same ID client-side and server-side e.g.
<asp:TextBox runat="server" ID="txtName" ClientIDMode="Static" />
Then you could trigger client-side validation on a button click by declaring a button like this:
<input type="submit" id="btnSubmit" onclick="ClientSideValidation(); return false;" value="Save"/>
The JavaScript function could look something like this:
<script type="text/javascript">
function ClientSideValidation() {
var txtName = document.getElementById("txtName");
if (txtName.value.length == 0) {
txtName.style.background = "#DE0000";
}
// Check other text boxes...
}
</script>
Thank you guys, I figured it out. This code does the job for me
.aspx.cs
CustomValidator customValidator = new CustomValidator();
customValidator.ControlToValidate = textBox.ID;
customValidator.ClientValidationFunction = "changeColorofTextBox";
customValidator.ValidateEmptyText = true;
customValidator.EnableClientScript = true;
e.Item.Controls.Add(customValidator);
.aspx
<script type="text/javascript">
function changeColorofTextBox(oSrc, args) {
if (args.Value.length > 0) {
args.IsValid = true;
}
else {
var ctrlid = oSrc.id;
var validatorid = document.getElementById(ctrlid);
ctrlid = validatorid.controltovalidate;
document.getElementById(ctrlid).style.backgroundColor = "Tomato";
args.IsValid = false;
}
}
</script>
This question is related to: Hide div on clientside click
The issue I am having is that after postback event from asp.net happens onClick any clientside changes made reset how can I keep the client side changes I am making.
Second question how can I get a variable from code behind and pass it into my javascript to perform a comparison.
Html:
<div runat="server" id="someDiv1" enableviewstate="true" >
<asp:LinkButton OnClientClick="Show_Hide_Display()"
ID="lbtnDiv1"
runat="server"
CausesValidation="true"
OnClick="lbtn_onClickServer">
</asp:LinkButton>
</div>
<div runat="server" class="tick" id="div2" style="display:none;" enableviewstate="true">
</div>
Javascript:
<script type="text/javascript">
function Show_Hide_Display() {
var div1 = document.getElementById("<%=someDiv1.ClientID%>");
var div2 = document.getElementById("<%=div2.ClientID %>");
if (div1.style.display == "" || div1.style.display == "block") {
div1.style.display = "none";
div2.style.display = "block";
}
else {
div1.style.display = "block";
div2.style.display = "none";
}
}
</script>
The OnClick event causes a postback like it should, on this occassion it checks if users, chosen username is available.
If it is available show a tick, if it isn't error.
I got the error working and am trying to program the tick on client side.
So OnClientClick I am able to toggle between some text and a tick. So I need to:
Get the bool result from code behind
After postback keep tick (if username is available)
I am almost there but can't quite figure the last two points out.
If you are using an UpdatePanel in your page, and assuming that div which you are trying to toggle is outside the control, you can always inject javascript on a partial postback:
Like for e.g. on your button's click event which executes on a partial postback make a call to ScriptManager.RegisterClientScriptBlock() --> How to retain script block on a partial postback?
Alternatively, you can append an end request handler. This is some javascript which should run after the partial postback. --> ASP.NET Register Script After Partial Page Postback (UpdatePanel)
The answer for the both questions lies of checking the boolean value send from the code behind.
1-----.in code-behind c#
protected void Page_Load(object sender, System.EventArgs e)
{
var linkbtn = (Button)Page.FindControl("lbtnDiv1");
linkbtn .Attributes.Add("onClick", "Show_Hide_Display('" + parameter+ "')");
}
2------- change your javascript
function Show_Hide_Display(parameter)
{
if( paramater=='true')
{
----your logic---
}
else
{
----your logic
}
}