I am validating a form from javascript.
The target is: if user do not enter value in a required field, an error message will show up and will disappear after few seconds.
BUT
The problem is: The error message don't show up and this is probably because from javascript I am failing to write error message in a label control. BUT, if I use javascript alert instead of displaying the label, it works.
The code:
Javascript
<script type="text/javascript">
function showConfirmation() {
$('div#confirmationDV').show();
setTimeout(function () {
$('div#confirmationDV').fadeOut(5000);
});
}
function validateRequiredField() {
if (document.getElementById("<%=txtOfferTitle.ClientID%>").value == "") {
alert("error.....");//this alert works.
document.all("<%=lblConfirmation.ClientID%>").innerHTML = "please enter your business name"; // this does not work
document.all("<%=lblConfirmation.ClientID%>").style.color = "red";
showConfirmation();
document.getElementById("<%=txtOfferTitle.ClientID%>").focus();
return false;
}
return true;
}
</script>
HTML
<div class="round-conf-box" id="confirmationDV">
<div class="round-conf-tl">
<div class="round-conf-tr"></div>
<div class="round-conf-background_color_top"></div>
</div>
<div class="round-conf-box-Content">
<asp:Label ID="lblConfirmation" runat="server" CssClass="confirmationLabel"></asp:Label>
</div>
<div class="round-conf-bl">
<div class="round-conf-br"></div>
<div class="round-conf-background_color_bottom"></div>
</div>
//...some other stuff
<asp:ImageButton ID="iBtnSave" runat="server" ImageUrl="~/images/createOffer.png"
onclick="iBtnSave_Click" OnClientClick="return validateRequiredField()" />
and in the code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
iBtnSave.Attributes.Add("onclick", "return validateRequiredField()");
//some other stuff
}}
Would be nice if anyone can help me to find my mistakes..
cheers
You mix jQuery and IE-Only JScript.
Make sure to only use jQuery or cross browser JavaScript
Change
function validateRequiredField() {
if (document.getElementById("<%=txtOfferTitle.ClientID%>").value == "") {
alert("error.....");
document.all("<%=lblConfirmation.ClientID%>").innerHTML = "please enter your business name";
document.all("<%=lblConfirmation.ClientID%>").style.color = "red";
showConfirmation();
document.getElementById("<%=txtOfferTitle.ClientID%>").focus();
return false;
}
return true;
}
to
$("#<%=iBtnSave.ClientID%>).click(function(e) {
var txtOffer = $("#<%=txtOfferTitle.ClientID%>");
var txtOfferLbl = $("#<%=lblConfirmation.ClientID%>");
if (txtOffer.val() == "") {
alert("error.....");
txtOfferLbl.text("please enter your business name");
txtOfferLbl.addClass("error");
showConfirmation();
txtOffer.focus();
e.preventDefault();
}
else {
txtOfferLbl.text("");
txtOfferLbl.removeClass("error");
}
});
Related
I am working on alpha.dubaiexporters.com. There is a search Panel containing two inputs Keyword and Categories. I wanted to validate Keyword part.
If the user entered less than three characters and clicked on Search button then the clientside message should be displayed saying the entered input should be more than 3 characters. I am not getting the clientside message.
The following is my code:
<input type="text" id="txtkeyword" name="s" runat="server" autocomplete="off">
<asp:Button ID="Search" class="dt-header-search-submit dt-button dt-button-danger" style="top:0px;width:226px;height:70px;" Text="Search" runat="server" onclick="doit" OnClientClick="return checkLength();" />
Below is my Javascript:
<script type="text/javascript">
function checkLength() {
var textbox = document.getElementById("txtkeyword");
if (textbox.value.length < 3) {
alert("The entered input should be 3 or more than 3 characters");
return false;
}
}
</script>
Code behind:
protected void doit(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtkeyword.Value))
{
try
{
String mainsearch1 = null;
mainsearch1 = txtkeyword.Value.Trim();
if (mainsearch1.Length > 2)
{
Response.Redirect("searchmain.aspx?mainsearch=" + mainsearch1 + "&querylevel=1");
}
}
catch (Exception ex)
{
}
}
else if (!string.IsNullOrEmpty(txtserach.Value))
{
try
{
String cat = null;
cat = txtserach.Value.Trim();
if (cat.Length > 2)
{
Response.Redirect("searchcat1.aspx?cat=" + cat);
}
}
catch (Exception ex)
{
}
}
}
}
I don't know why its not calling javascript function.
Expected output: I want this alert message when user enter less than three letters in txtkeyword textbox.
It works fine, have a try please :)
function checkLength() {
debugger;
var textbox =$get("<%=txtkeyword.ClientID%>"); //document.getElementById("<%=txtkeyword.ClientID%>")
if (textbox.value.length < 3) {
alert("The entered input should be 3 or more than 3 characters");
return false;
}
}
Note: you cant access a control directly when runat="server" is there
I am using the following code to delete records from database using confirmation.
ASP.NET
<asp:TextBox ID="text_delete" Width="70%" Height="60px" ValidationGroup="del" CssClass="textbox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="required_desc" CssClass="validator" ValidationGroup="del" ControlToValidate="text_delete" ErrorMessage="Reason Required" runat="server">Reason Required</asp:RequiredFieldValidator>
<asp:Button ID="button_delete" CssClass="button" ValidationGroup="del" Text="Delete" runat="server" OnClientClick="Confirm()" OnClick="button_delete_Click" />
JavaScript
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to delete this data?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
C#
protected void button_delete_Click(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
// Delete the data
}
if (confirmValue == "No")
{
// Do not delete data
}
}
But here i want the user to enter the reason to delete in textbox first and only after that the confirm popup should appear. Even though i am using a required field validator the validator is fired only after the popup window. How can i fire the validator first and only if the reason is entered the popup window for delete confirmation should appear. How can i do this?
You can invoke the required field validation within a script using Page_ClientValidate(), or Page_ClientValidate("group name") if you want to be more specific.
if(Page_ClientValidate()){
....popup confirmation code
....
}
Working RequiredFieldValidator along with javascript
The email id is entered into a textbox and the validation for email is applied but there seems to be an error that the whole function is probably not called during execution
<head runat="server">
<title></title>
<script type="text/javascript">
function IsValidUrl()
{
var emailbox = document.getElementById('<%=TextBox4.Text %>');<!--textbox4 is used to receive the email entered by the user-->
var email = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (textbox.value.length > 0)<!--the email field should be non empty-->
{
if (email.test(emailbox.value))
{
return true;
}
else
{
alert("Please enter valid Email");<!--incase of an invalid email-->
return false;
}
}
else
{
alert("please enter text");
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" style="margin-left: 340px" Text="Submit" Width="96px" OnClick="Button1_Click1" OnClientClick="javascript:IsValidUrl();"/>
</form>
</body>``
There seems couple of issue with the javascript's IsValidURL function so please replace it with below code.
function IsValidUrl()
{
var emailbox = document.getElementById('<%=TextBox4.ID %>');
var email = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (emailbox.value.length > 0)
{
if (email.test(emailbox.value))
{
return true;
}
else
{
alert("Please enter valid Email");
return false;
}
}
else
{
alert("please enter text");
return false;
}
}
There are mainly two problems
<%=TextBox4.Text %> here you want id of the textBox but you are fetching value of the textBox.
textbox.value.length you want to check value of the TextBox4 but its variable name is emailbox, not textbox.
So I have just corrected those.
Hope this helps you.
Probably your function is working correctly but the page gets submitted even after the validation so replace below:
OnClientClick="javascript:IsValidUrl();"
with
OnClientClick="return javascript:IsValidUrl();"
Edit
Just figured an error in your JS code if (textbox.value.length > 0) line should be if (emailbox.value.length > 0) so try with replace it.
Another issue I found in document.getElementById('<%=TextBox4.Text %>') which should be document.getElementById('<%=TextBox4.ID %>') and in case of using master pages it should be document.getElementById('<%=TextBox4.ClientID %>') so try replacing it too.
Hope this will help !!
I am using this to check if fields are empty. The problem is, the error message is never thrown when a field is empty, it allows submission. Is it because I am trying to run onclick and onclientclick on the button? This is my syntax
HTML
<asp:Button ID="main1212" runat="server" Text="Check If JS Works"
OnClick="DoSomethingDoNothing_OnClick" OnClientClick="return ValidateData();" />
JS
<script type="text/javascript">
function ValidateData() {
var main1212, dropdownselection, dropdownselection1, field21
main1212 = document.getElementByID("txt313").value;
dropdownselection = document.getElementByID("dropdownlist1").value;
dropdownselection1 = document.getElementByID("dropdownlist11").value;
field21 = document.getElementByID("txt12").value;
if (main1212 == '')
{
alert("Error");
return false;
}
if (dropdownselection == '')
{
alert("Error");
return false;
}
if (dropdownlist1 == '')
{
alert("Error")
return false;
}
if (field21 == '')
{
alert("Error");
return false;
}}
</script>
EDIT
If I open the browser console and press the button that should run my script their are no errors displayed?
It's missing a semi-colon in this line (not sure) of the function ValidateData:
var main1212,dropdownselection,dropdownselection1,field21;
(it's good to avoid extra spaces and also not create variables for this)
And it could be more simple, or like this:
window.onload=function(){document.getElementById('main1212').onclick=function(){ValidateData();};}
I have a html input button like this
<input type="button" id="send_button" class="form_button" value="Send" onclick="return validateTextBoxes();" runat="server" />
And also I have javascript
<script language="javascript">
function validateTextBoxes()
{
var reading1 = document.getElementById('<%= meterReading1.ClientID%>').value;
var error = document.getElementById('<%= lblError.ClientID%>');
var btn = document.getElementById('<%= send_button.ClientID%>');
var ValidationExpression = /[\d]/;
if (reading1 == "" )
{
error.innerHTML = "Please enter Water Meter Reading.";
return false;
}
else if(!ValidationExpression.test(reading1)) {
error.innerHTML = "Please enter valid Meter Reading(It Contains only numbers)";
return false;
}
else
{
error.innerHTML = "";
return true;
}
}
</script>
And I am also calling this server click event in the code behind file
this.send_button.ServerClick += new System.EventHandler(this.send_ok);
So here is the problem when javscript returns true its not firing the serverclick event.
Please help me where I am doing wrong(I am using framework 1.1)
Thanks
I had this problem once and I actually had to do something like this:
onclick="if (validateTextBoxes()) { return true; } else { return false; }"
You absolutely should not have to do this and it made no sense to me why it would be have this way, but alas, I tried it and it worked :(