I am trying to use a customvalidator to validate a DIV form and then close it if there is no validation errors. Below is my code, I can't get my custom validator to work, when I click submit, nothing validates, not sure what's wrong. Please advice. Thanks.
function validateRedemptionDialog(src, args) {
var rDate = document.getElementById('<%=uitxtRedemptionDate.ClientID%>').value;
if (rDate == "") {
args.IsValid = false;
return;
}
args.IsValid = true;
}
function closeRedemptionDialog() {
$('#dialog_Active_Redemption_confirm').dialog('close');
}
<div id="dialog_Active_Redemption_confirm" style="display: none">
<div class="section_body">
<div class="section_body_content">
<div class="row">
<asp:Label runat="server" ID="uilblRedemptionDate" Text="<%$ Resources:MembersNContactsManagerResources, uigrdhdrTransDate %>"
CssClass="label">
</asp:Label>
<asp:TextBox ID="uitxtRedemptionDate" runat="server" CssClass="text DatePicker" Style="width: 120px;
margin-right: 2px;">
</asp:TextBox>
<asp:CustomValidator ID="ctvtxtCamDateEnd" runat="server" ClientValidationFunction="validateRedemptionDialog"
ControlToValidate="uitxtRedemptionDate" ErrorMessage='<img src="../Images/icons/error.png" style="vertical-align:middle"/> XXX!'
Font-Names="arial" Font-Size="X-Small" SetFocusOnError="True" Display="Dynamic" />
</div>
<div class="row">
<asp:Label runat="server" ID="uilblRedemptionAmountSpent" Text="<%$ Resources:MembersNContactsManagerResources, uilblRedemptionAmountSpent %>"
CssClass="label">
</asp:Label>
<asp:TextBox ID="uitxtRedemptionAmountSpent" runat="server" Style="width: 120px;">
</asp:TextBox>
</div>
<div class="row">
<ul class="inline" style="margin-left: 137px; padding: 3px;">
<li><span class="button grey_btn">
<%--Submit button--%>
<asp:Button ID="uibtnRedemption" runat="server" Text="<%$ Resources : MembersNContactsManagerResources, uilblSubmit %>" OnClientClick="javascript:closeRedemptionDialog();"/>
<span> </span> </span></li>
</ul>
</div>
</div>
</div>
</div>
The validator will not validate empty text with your current configuration.
Set ValidateEmptyText to true if you need it to fire even when the user has entered nothing.
A CustomValidator does not need to have a ControlToValidate. If you need to validate in any case, you should leave that property empty.
Related
I'm having problems with integrating JavaScript to ASP.NET. I want to use jQuery or even Vanilla JavaScript to do some client side operations but I'm unable to access HTML and ASP.NET Server Controls. I have tried many solution, just like using <%= element.ClientID %> but none worked for me. I'm unable to identify my fault, please help me identifiying.
Alread Tried:
RegisterClientScriptBlock
Include JavaScript File Directly
$("#<% element.ClientID %>")
document.getElementById("<%= element.ClientID %>");
Using HTML control instead Server & vice versa.
new_quiz.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/teacher_quizes/teacher_quizes.master" AutoEventWireup="true" CodeBehind="new_quiz.aspx.cs" Inherits="onlineQuiz_bsef17m35.teacher_quizes.new_quiz" %>
<asp:Content ID="Content1" ContentPlaceHolderID="quizes" runat="server">
<div class="form p-2">
<div class="form-group p-1">
<asp:Label runat="server" Text="Quiz Title"></asp:Label><br />
<small class="text-danger">The title of your quiz</small>
<input runat="server" type="text" maxlength="64" id="title"
class="form-control"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="title"
ErrorMessage="Title is required"></asp:RequiredFieldValidator>
</div>
<div class="form-group p-1">
<asp:Label runat="server" Text="Quiz Description"></asp:Label><br />
<small class="text-danger">Please describe this quiz</small>
<textarea runat="server" id="description" class="form-control" rows="2"
maxlength="128">
</textarea>
<asp:RequiredFieldValidator runat="server" ControlToValidate="description"
ErrorMessage="Description is required" CssClass="text-warning text-muted">
</asp:RequiredFieldValidator>
</div>
<div class="form-group p-1">
<asp:Label runat="server" Text="Maximum Marks"></asp:Label><br />
<small class="text-danger">The maximum achiveable marks for this quiz, between 1 and 1000</small>
<input runat="server" type="number" min="1" max="100" id="maxMarks"
class="form-control"/>
<asp:RangeValidator MinimumValue="1" MaximumValue="1000"
runat="server" ControlToValidate="maxMarks" CssClass="text-warning"
ErrorMessage="Please choose a number between 1 and 100">
</asp:RangeValidator>
</div>
<div class="form-group p-1">
<asp:Label runat="server" Text="Passing Marks"></asp:Label><br />
<small class="text-danger">The passing marks for this quiz, between 1 and 1000 and lesser than or equal to total marks</small>
<input runat="server" type="number" min="1" max="100" id="passingMarks"
class="form-control"/>
<asp:RangeValidator MinimumValue="1" MaximumValue="1000"
runat="server" ControlToValidate="passingMarks" CssClass="text-warning"
ErrorMessage="Please choose a number between 1 and 100">
</asp:RangeValidator>
</div>
<div class="form-group p-1 card mb-2">
<div><b runat="server" id="questions">Quesions</b></div>
<div class="form-group">
<asp:Label runat="server" Text="Question"></asp:Label><br />
<asp:TextBox runat="server" ID="question" CssClass="form-control"/>
<asp:Label runat="server" Text="Type of Question"></asp:Label><br />
<select runat="server" id="questionType" class="form-control"
onchange="questionTypeChange()"></select>
<div runat="server" id="questionOptions">
<small>Please check checkbox in front of Options to denote an option as true</small>
<div class="form-group">
<asp:Label runat="server" Text="Option 1"></asp:Label><br />
<input runat="server" type="text" maxlength="64" id="questionOption1"
class="form-control" />
<input runat="server" type="checkbox" id="questionOption1Validity"
class="input-group-append"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="questionOption1"
ErrorMessage="Option 1 is required!" CssClass="text-danger">
</asp:RequiredFieldValidator>
</div>
<div class="form-group">
<asp:Label runat="server" Text="Option 1"></asp:Label><br />
<input runat="server" type="text" maxlength="64" id="questionOption2"
class="form-control" />
<input runat="server" type="checkbox" id="questionOption2Validity"
class="input-group-append"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="questionOption2"
ErrorMessage="Option 2 is required!" CssClass="text-danger">
</asp:RequiredFieldValidator>
</div>
<div class="d-flex flex-row-reverse">
<button class="btn btn-sm btn-primary">Add another Option</button>
</div>
</div>
</div>
</div>
</div>
</asp:Content>
new_quiz.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace onlineQuiz_bsef17m35.teacher_quizes
{
public partial class new_quiz : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
return;
}
DatabaseEntities db = new DatabaseEntities();
var quizes = db.getQuestionTypes().ToArray();
questionType.DataSource = quizes;
questionType.DataBind();
if (questionType.Value == "Multiple Choice")
{
questionOptions.Visible = true;
} else
{
questionOptions.Visible = false;
}
/* register client scripts */
Type scriptType = this.GetType();
String scriptName = "script";
String scriptUrl = "./new_quiz.js";
String scriptText = File.ReadAllText(Server.MapPath(scriptUrl));
ClientScriptManager scriptManager = Page.ClientScript;
if (!scriptManager.IsClientScriptBlockRegistered(scriptType, scriptName))
{
scriptManager.RegisterClientScriptBlock(scriptType, scriptName, scriptText, true);
}
}
}
}
new_quiz.js
function questionTypeChange() {
const element = document.getElementById("<%= question.ClientID %>");
console.log(element);
}
First check if your jQuery is loaded correctly.
Open console (press F12) and type "jQuery" and enter - you should get something back. If you get "not defined" - then make sure you do load it.
Then, you should be able to access your HTML, via jQuery selector.
More info here: https://www.w3schools.com/jquery
Real problem was that I was using external script. ASP.NET Tag in external script does not work. For that I used jQuery pattern matching to find controls.
To find button with ID="saveButton", I used $("[id$=saveButton]") that results in all Controls having an ID ending with saveButton.
Above works, because ASP.NET appends original ID to some random ID generated while compilation, so final html id always ends with original id given in markup.
I have a RadioButtonList inside a repeater and I want to clear the checked value on the OnChange of a textbox
<asp:Repeater ID="QuestionsRpt" runat="server">
<HeaderTemplate>
<div class="form-horizontal form-condensed">
</HeaderTemplate>
<ItemTemplate>
<div class="form-group">
<label class='col-sm-6 control-label' style="text-align:left"><span id="Question" runat="server"><%# Eval("Name_" + UserLanguage.ToUpper()) %></span> <i class="fa fa-question-circle" runat="server" visible='<%# Eval("Description_" + UserLanguage.ToUpper()).ToString() != ""%>' data-toggle="tooltip" title='<%# Eval("Description_" + UserLanguage.ToUpper()).ToString()%>'></i></label>
<div class="col-sm-6">
<asp:RadioButtonList ID="RadioButtonList" runat="server" CssClass="RadioButtonList" AutoPostBack="true"
DataSource='<%# (Eval("ListOfChoice_" + UserLanguage.ToUpper()).ToString()).Split(";".ToCharArray()) %>'
Visible='<%# (Convert.ToInt32(Eval("Type_IsSingleChoice")) == 1)%>'>
</asp:RadioButtonList>
<input type='text' id="OtherOptionTB" runat="server"
placeholder='<%# GetLocalResourceObject("Other Option") %>' class="form-control otherOption input-sm" value=''
autocomplete="off" visible='<%# Eval("AllowFreeText")%>' onchange="ResetRadioButtonList()"/>
</div>
</div>
<br />
</ItemTemplate>
<FooterTemplate>
</div>
</FooterTemplate>
Here is the jquery:
<script type="text/javascript">
function ResetRadioButtonList() {
$(event.target).closest('.form-group').find('.RadioButtonList').prop('checked', false);
}
When I log $(event.target).closest('.form-group').find('.RadioButtonList') I do get the the RadioButtonList but I can't seem to figure out how to clear it correctly.
I found the problem...
I need to access all the inputs in my RadioButtonList
Here is the updated Jquery:
function ResetRadioButtonList() {
$(event.target).closest('.form-group').find('.RadioButtonList').find('input:radio').prop('checked', false);}
I am working on Asp.net form as follows
<form runat="server" id="form">
<label>Select Category <span>*</span></label>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Mobiles</asp:ListItem>
<asp:ListItem>Electronics and Appliances</asp:ListItem>
<asp:ListItem>Cars</asp:ListItem>
<asp:ListItem>Bikes</asp:ListItem>
<asp:ListItem>Furniture</asp:ListItem>
<asp:ListItem>General</asp:ListItem>
</asp:DropDownList>
<div class="clearfix"></div>
<label>Ad Title <span>*</span></label>
<asp:TextBox ID="txt_title" class="phone" runat="server"></asp:TextBox>
<div class="clearfix"></div>
<label>Ad Description <span>*</span></label>
<%--<textarea class="mess" placeholder="Write few lines about your product"></textarea>--%>
<asp:TextBox ID="txt_Body" class="mess" placeholder="Write few lines about your product" TextMode="multiline" Style="resize: none" Width="770px" Height="150px" Wrap="true" runat="server" Font-Bold="True"></asp:TextBox>
<div class="clearfix"></div>
<div class="upload-ad-photos">
<label>Photos for your ad :</label>
<div class="photos-upload-view">
<asp:ImageButton ID="ImageButton1" UseSubmitBehavior="false" OnClientClick="return chooseFile();" ImageUrl="Images/Capture.JPG" runat="server" />
<asp:FileUpload ID="FileUploadControl" runat="server" Visible="False" />
<div id="messages">
<p>Status Messages</p>
</div>
</div>
<div class="clearfix"></div>
</div>
<div class="personal-details">
<label>Your Name <span>*</span></label>
<asp:TextBox ID="txt_name" class="name" runat="server"></asp:TextBox>
<div class="clearfix"></div>
<label>Your Mobile No <span>*</span></label>
<asp:TextBox ID="txt_phn" class="phone" runat="server"></asp:TextBox>
<div class="clearfix"></div>
<label>Your Email Address<span>*</span></label>
<asp:TextBox ID="txt_email" class="email" runat="server"></asp:TextBox>
<div class="clearfix"></div>
<p class="post-terms">By clicking <strong>post Button</strong> you accept our Terms of Use and Privacy Policy</p>
<asp:TextBox ID="post_sub" Text="Post" type="submit" runat="server"></asp:TextBox>
<div class="clearfix"></div>
</form>
Where I want to call a hidden fileupload when Imagebutton is clicked using JavaScript as follows:
<script type="text/javascript">
function chooseFile() {
document.getElementById("#FileUploadControl").click();
alert("grt");
return false;
}
</script>
But, I was not able to call the function instead page reloads, as you can see I am returning false in the function also. Please guide me to make this work.
You have set the Visible property of the FileUpload Control to false. Therefore it does not exist on the client side. The Visible property is not the same as display:none in HTML/CSS.
You should do something like this:
<span style="display: none">
<asp:FileUpload ID="FileUploadControl" runat="server" />
</span>
And it's always better to use the ClientID instead of hard coding the ID of the FileUpload Control.
<script type="text/javascript">
function chooseFile() {
document.getElementById("<%= FileUploadControl.ClientID %>").click();
return false;
}
</script>
When you use document.getElementById you shouldn't mention # since it already searches for id attribute, in your current state it will look for id #FileUploadControl which is not your element id. change your code to this:
function chooseFile() {
document.getElementById("FileUploadControl").click();
alert("grt");
return false;
}
<form runat="server" id="form">
<div class="photos-upload-view">
<img id="ImageButton1" OnClick="return chooseFile();" src="https://maxcdn.icons8.com/office/PNG/512/Computer_Hardware/mouse_left_click-512.png" style="widdth:40px;height:40px;" />
<input type="file" ID="FileUploadControl" runat="server" style="display:none;" />
</div>
</form>
Yes, number one is you using # of you document.getElementById("#FileUploadControl") it's wrong and you should use it without # document.getElementById("FileUploadControl").
second thing if you use Visible="False" attribute it not rendering the HTML element, without that you can use below two methods.
FileUploadControl.Style["visibility"] = "hidden" in your backend file
using following css class for hide
function chooseFile() {
document.getElementById("FileUploadControl").click();
alert("grt");
return false;
}
.setDisplayNone {
display:none;
}
<asp:FileUpload ID="FileUploadControl" runat="server" CssClass="setDisplayNone" />
I try to ajaxify RadNumericTextBoxs in Edit Form of Rad grid using (RadAjaxManager or RadAjaxManagerProxy) but i failed .
all i want to do is :
when text changed of (txt_CashAndEquivalents,txt_ShortTermInvestments) sum the values of both text boxes and set the result in txt_OneTotal without full postback .
<EditFormSettings EditFormType="Template">
<EditColumn UniqueName="EditCommandColumn1" FilterControlAltText="Filter EditCommandColumn1 column">
</EditColumn>
<FormTemplate>
<div class="FinancePositioncontainers">
<div class="FinancePosition-container" id="decorationZone">
<h4>Finance</h4>
<fieldset>
<legend>List</legend>
<div class="formRow" style="padding-right: 10px; padding-left: 10px;">
<h5>Bal</h5>
<label for="txt_CashAndEquivalents">bal1:</label>
<telerik:RadNumericTextBox ID="txt_CashAndEquivalents" runat="server" Text='<%# Eval("CashAndEquivalents")%>' Type="Number" DataType="System.Decimal" Width="160" NumberFormat-GroupSizes="3" AutoPostBack="True" TabIndex="1" OnTextChanged="txt_CashAndEquivalents_TextChanged"></telerik:RadNumericTextBox>
<div>
</div>
<label for="txt_ShortTermInvestments">bal2:</label>
<telerik:RadNumericTextBox ID="txt_ShortTermInvestments" runat="server" Text='<%# Eval("ShortTermInvestments")%>' Type="Number" DataType="System.Decimal" Width="160" NumberFormat-GroupSizes="3" TabIndex="2" AutoPostBack="True" OnTextChanged="txt_CashAndEquivalents_TextChanged"></telerik:RadNumericTextBox>
<div>
</div>
<hr />
<label for="txt_OneTotal">total :</label>
<telerik:RadNumericTextBox ID="txt_OneTotal" runat="server" ReadOnly="true" Type="Number" DataType="System.Decimal" Width="160" NumberFormat-GroupSizes="3"></telerik:RadNumericTextBox>
<div>
</div>
</div>
<asp:LinkButton ID="btnUpdate" runat="server" CommandName='<%# (Container is GridEditFormInsertItem) ? "PerformInsert" : "Update" %>'
ValidationGroup="Main" CssClass="btn btn-primary btn-xs white_cr"><span class="glyphicon glyphicon-floppy-disk"></span> <%# (Container is GridEditFormInsertItem) ? "Uppdate" %>
</asp:LinkButton>
<asp:LinkButton ID="btnCancel" runat="server" CausesValidation="False" CommandName="Cancel"
CssClass="btn btn-primary btn-xs white_cr"><span class="glyphicon glyphicon-ban-circle"></span>Cancel</asp:LinkButton>
<br />
<br />
</div>
</div>
</FormTemplate>
</EditFormSettings>
One approach you can consider is to utilise the client event, OnValueChanged of RadNumbericTextBox control, instead of the server side event.
For example,
<telerik:RadNumericTextBox ID="txt_CashAndEquivalents" runat="server" Text='<%# Eval("CashAndEquivalents")%>' Type="Number" DataType="System.Decimal" Width="160" NumberFormat-GroupSizes="3" TabIndex="1">
<ClientEvents OnValueChanged="DoSum" />
</telerik:RadNumericTextBox>
<script type="text/javascript">
function DoSum(sender, eventArgs)
{
var txt_ShortTermInvestments = $find('<%=txt_ShortTermInvestments.ClientID %>');
var txt_OneTotal = $find('<%=txt_ShortTermInvestments.ClientID %>');
var val_CashAndEquivalents = sender.get_value();
var val_ShortTermInvestments = txt_ShortTermInvestments.get_value();
txt_OneTotal.set_value(val_CashAndEquivalents + val_ShortTermInvestments);
}
</script>
Above code is just demonstrating the idea and hasn't been tested. So give it a go and see if it works for you or not.
For more details on the available client side events, please refer to the following link.
http://docs.telerik.com/devtools/aspnet-ajax/controls/numerictextbox/client-side-programming/radnumerictextbox-client-object#radnumerictextbox-client-object
I have a login box that I need to have submitted when enter is pressed. Below you are going to find part of the code. Please any help would be appreciated.
<div class="box-login clearfix">
<div class="box-login-header">
<h3>
Registered Users</h3>
</div>
<div>
<asp:Label ID="LblMessage" runat="server" ForeColor="Red"></asp:Label>
<asp:RequiredFieldValidator ID="Rfv_LoginId" runat="server" ControlToValidate="TextLogInId"
ErrorMessage="Login Id is required" ValidationGroup="A" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RevLoginId" runat="server" ControlToValidate="TextLogInId"
ErrorMessage="Login id does not contain spaces,double quotes or +><=';:,|/"
ValidationExpression="[^ "+><=':,|/]*$" ValidationGroup="A" Display="Dynamic"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="Rfv_Password" runat="server" ControlToValidate="TextPassword"
ErrorMessage="Password is required" ValidationGroup="A" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="CvPassword" runat="server" ClientValidationFunction="ValidatePassword"
ControlToValidate="TextPassword" ErrorMessage="" Display="Dynamic"></asp:CustomValidator>
<asp:RegularExpressionValidator ID="RevPassword" runat="server" ControlToValidate="TextPassword"
ErrorMessage="Space is not allowed" ValidationExpression="[^ ]*$" ValidationGroup="A"
Display="Dynamic"></asp:RegularExpressionValidator>
<asp:Label ID="LblPassword" runat="server" ForeColor="#FF0066"></asp:Label>
</div>
<p>
Please enter your GoCCL.com Login ID & Password below</p>
<ul>
<li>
<label for="cloginid">
Login ID:</label>
<asp:TextBox ID="TextLogInId" runat="server" CssClass="text-box" MaxLength="16" onblur="ClearMessage()"></asp:TextBox>
</li>
<li>
<label for="cpassword">
Password:</label>
<asp:TextBox ID="TextPassword" runat="server" TextMode="Password" CssClass="text-box"
MaxLength="16" onblur="ClearMessage()"></asp:TextBox>
</li>
</ul>
<asp:LinkButton ID="btnForgotPassword" CssClass="forgot" runat="server" Text="Forgot your Login ID or Password?"
OnClick="btnForgotPassword_Click"></asp:LinkButton>
<asp:ImageButton ID="CmdLogin" CssClass="btn-login" OnClick="CmdLogin_OnClick" OnClientClick="ClearMessage()"
runat="server" ImageUrl="/stylesheets/bookccl/images/button/btn-login.gif" CausesValidation="true" />
<div class="box-login-fotter clearfix">
<p>
<strong>New to GoCCL? </strong>
<asp:LinkButton ID="btnRegistration" runat="server" Text="Register Now" CssClass="register-new"
OnClick="btnRegistration_Click"></asp:LinkButton>
to join the fun!</p>
</div>
</div>
You could wrap it in a Panel control and set the DefaultButton to the button you want invoked when pressing Enter. There are also other options explored here:
http://www.beansoftware.com/asp.net-tutorials/accept-enter-key.aspx