i am having javascript function written to check if the dropdown value from an aspx page has value "Completed" or "Cancelled".if it is then check if the date and time is not null.
But the function never fires. the code is below.
function EnableValidator() {
var drp = document.getElementById('<%=drpcallstatus.ClientID %>');
var txt = drp.options[drp.selectedIndex].text;
var dt = document.getElementById('<%=txtcompletedate.ClientID %>');
var ct = document.getElementById('<%=txtcomptime.ClientID %>');
if ((txt == "Completed" | txt=="Cancelled") && (dt===null | ct===null)) {
alert("Please Enter the Completed Date and Time");
return false;
}
The function is called from asp.net button
<asp:Button ID="btnsubmit" runat="server" Text="Submit" OnClientClick="return EnableValidator()" onclick="btnsubmit_Click" />
try :
if ((txt == "Completed" || txt=="Cancelled") && (dt===null || ct===null)) {
alert("Please Enter the Completed Date and Time");
return false;
}
You have to use || for it works.
The problem here is that you are not using the correct operator for your OR.
if ((txt == "Completed" || txt=="Cancelled") && (dt===null || ct===null)) {
...
}
Use double pipe characters || for an OR operator in a conditional expression.
Related
I am developing asp.net application, in that i have a page contains gridview with text boxes,
in that i need to validate to fill atleast one text box in that gridview.
I googled many pages, but i have found only check box validation like this,
when save button click, i need to validate to fill atleast one text box in deposit amount in that gridview..
please any answers would be appreciated..
Use RequiredFieldValidator
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtAmount" ErrorMessage="Fill This"></asp:RequiredFieldValidator>
<script type="text/javascript">
function validateTextBox() {
//get target base & child control.
var TargetBaseControl = document.getElementById('<%=this.Gridview1.ClientID%>');
var TargetChildControl1 = "txtDepositAmount";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for (var n = 0; n < Inputs.length; ++n)
if (Inputs[n].type == 'text' && Inputs[n].id.indexOf(TargetChildControl1, 0) >= 0)
if (Inputs[n].value != "") return true;
alert('Enter Atleast One Deposit Amount!');
return false;
}
</script>
<asp:ImageButton ID="btnSave" runat="server" ValidationGroup="valInsert" ImageUrl="~/images/save6.png"
Width="40px" Height="40px" OnClientClick="javascript:return validateTextBox();" OnClick="btnSave_Click" ToolTip="Save" />
You can use a CustomValidator and jQuery to check if at least one TextBox has text in it.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="At least one TextBox is required" ClientValidationFunction="validateMyTextBoxes"></asp:CustomValidator>
<script type="text/javascript">
function validateMyTextBoxes(oSrc, args) {
var isValid = false;
$("#<%= GridView1.ClientID %> input[type=text]").each(function () {
if ($(this).val() != "") {
isValid = true;
}
})
args.IsValid = isValid;
}
</script>
i want to call my java script function return value to my code
i have a function like this..(this i wrote in my java script)
function GetSex()
{
var sex = EIDAWebComponent.GetSex();
if(sex == 'M')
return "Male";
if(sex == 'F')
return "Female";
if(sex == 'X')
return "Unknown";
}
my code:
<td>
<span>Sex: </span>
</td>
<td>
<span id="Sex_PDLabel" runat=server></span>
</td>
how i can call this return value in my code?
i want to get corresponding value to any variable. so try to write code something like this:
ScriptManager.RegisterStartupScript(DirectCast(HttpContext.Current.Handler, Page), GetType(Page), "GetSEx", "GetSex()", True)
Dim SexVAl = Sex_PDLabel.InnerText
but my sexVal Always getting empty string.i dont know why? what is the problem with my code?
any help is very appriciable..
One of the approaches is to store the value in a hidden field.
Add following to your ASP.NET markup:
<asp:HiddenField id="hdnField" runat="server" />
and call:
document.getElementById('<%= hdnField.ClientID %>').value = GetSex();
In codebehind the value will be accessible as:
var val = hdnField.Value;
Use this.
aspx:
Create a hidden field to store the value.
<input type="hidden" id="txtHidden" runat="server" />
javascript code:
function GetSex()
{
var sex = EIDAWebComponent.GetSex();
alert(sex);
if(sex == 'M')
document.getElementById("txtHidden").value= "Male";
else if(sex == 'F')
document.getElementById("txtHidden").value = "Female";
else if(sex == 'X')
document.getElementById("txtHidden").value = "Unknown";
else
document.getElementById("txtHidden").value = "none";
}
Call from ASP.NET code:
ScriptManager.RegisterStartupScript((Page)(HttpContext.Current.Handler),
typeof(Page), "GetSex", "GetSex();", true);
String value = txtHidden.Value;
When I click my Button to perform the validation, the validation happens correctly on the server side, but at the same time my client side validation always says the page is valid even when the page is not valid on the server side.
HTML
<telerik:RadComboBox ID="PURSubAccounts" runat="server" Width="150" EmptyMessage=" ---" Font-Bold="true"></telerik:RadComboBox>
<asp:RequiredFieldValidator id="PurSubValidation" runat="server" ErrorMessage="!!!" Display="Dynamic" Font-Bold="true" Font-Italic="true" ForeColor="Red" InitialValue="" ControlToValidate="PURSubAccounts" EnableClientScript="true"></asp:RequiredFieldValidator>
<asp:Button ID="CreateButton" runat="server" CausesValidation="true" OnClick="CreateButton_Click" OnClientClick="ValidateME();" />
JavaScript
function ValidateME() {
if (Page_IsValid) {
alert("Valid");
} else {
alert("NOT Valid");
}
}
VB Code
Protected Sub CreateButton_Click(sender As Object, e As EventArgs)
If Page.IsValid Then
msgbox("Valid")
Else
msgbox("NOT Valid")
End If
End Sub
So when I click the button, The vb messagebox says "NOT Valid" and the clientside Alert says "Valid" whilst my error messages on the requiredfieldvalidators are correctly displayed.
I have tried using the Page_ClientValidate() but that also returns true whilst serverside returns false.
How do I go about getting the validations to agree?
Use Custom validor rather than Required field validator:
<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="validateCombo" ErrorMessage="You must select an item with even value" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
For your client side validation :
function validateCombo(source, args)
{
args.IsValid = false;
var combo = $find("<%= RadComboBox1.ClientID %>");
var text = combo.get_text();
if (text.length < 1)
{
args.IsValid = false;
}
else
{
var node = combo.findItemByText(text);
if (node)
{
var value = node.get_value();
if (value.length > 0 && value % 2 == 0)
{
args.IsValid = true;
}
}
else
{
args.IsValid = false;
}
}
}
Please try this for server side validation and let me know if it works for you.
string selectedValue = RadComboBox1.SelectedValue;
if (selectedValue != null && selectedValue.Length > 0)
{
try
{
int value = Convert.ToInt32(selectedValue);
if (value % 2 == 0)
args.IsValid = true;
else
args.IsValid = false;
}
catch (Exception ex)
{
args.IsValid = false;
}
}
else
args.IsValid = false;
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
function ValidatePhoneNumbers() {
var phone = document.getElementById('txtPhone1');
var mobile =document.getElementById('txtPhone2');
alert(phone.value);
if ((phone.value == null || phone.value == "") && (mobile.value == null || mobile.value == "")) {
alert('something');
return false;
}
else {
alert('something');
return true;
}
}
</script>
<tr>
<td>
<label for="txtPhone1">
Phone :</label>
</td>
<td>
<telerik:RadNumericTextBox ID="txtPhone1" runat="server" Text='<%# Bind("Phone_One") %>' Type="Number" Skin="Windows7" CssClass="txt">
<numberformat allowrounding="false" keepnotroundedvalue="False" GroupSeparator=""></numberformat>
</telerik:RadNumericTextBox>
<asp:CustomValidator ID="rqfldPhone1" runat="server" ControlToValidate="txtPhone1"
Display="Dynamic" ErrorMessage="*" ValidationGroup="Submit" ToolTip="Enter Phone Number" ></asp:CustomValidator>
</td>
<telerik:RadButton ID="btnUpdate" runat="server" Text='<%# (Container is GridEditFormInsertItem) ? "Insert" : "Update" %>'
CommandName='<%# (Container is GridEditFormInsertItem) ? "PerformInsert" : "Update" %>'
Skin="Windows7" ValidationGroup="Submit">
When i add "OnClientClicked" to RadButton to call javaScript ( "return ValidatePhoneNumbers" ) in javaScript It showing NULL WHY ?
there are 2 rad textbox txtphone1 and txtphone2 ,
Actually i want to validate these textbox , if any one is filled no prob otherwise i need to show A error/warning msg.
pls help me
Actually ".value" is not shownig in javascript (document.GetelementById.value)
When you are working with telerik controls the javascript to find controls and do operations is different that of we work with normal html and javascript:
To find radcombox:
$find("<%=RadComboBox1.ClientID %>");//for example
Let work with your problem:
var phone=$find("<%=txtPhone1.ClientID %>");
var mobile=$find("<%=txtPhone2.ClientID %>");
alert(phone.get_value());//use get_value() to get the value of radcombobox
if ((phone.get_value() == null || phone.get_value() == "") && (mobile.get_value() == null || mobile.get_value()== "")) {
alert('something');
eventArgs.set_cancel(true);
}
else {
alert('something');
}
}
The OnClientClicked event will run a function by name with 2 parameters, these are akin to that used by .NET event handlers (sender and eventArgs). The Telerik controls don't cancel the action in the same manner as general HTML objects in that return false; doesn't cancel a post back. Instead, the Telerik API provides a set_cancel() function in the eventArgs parameter.
function ValidatePhoneNumbers(sender, eventArgs) {
var phone = document.getElementById('<%= txtPhone1.ClientId %>'); // Corrected as per my comment
var mobile =document.getElementById('<%= txtPhone2.ClientId %>'); // Corrected as per my comment
alert(phone.value);
if ((phone.value == null || phone.value == "") && (mobile.value == null || mobile.value == "")) {
alert('something');
eventArgs.set_cancel(true);
}
else {
alert('something');
}
}
You don't need to set the OnClientClicked="return ValidatePhoneNumbers" instead I would recomment using OnClientClicking ="ValidatePhoneNumbers" (see: http://www.telerik.com/help/aspnet-ajax/button-onclientclicking.html)
For more information regarding client side event handlers, see: http://demos.telerik.com/aspnet-ajax/menu/examples/programming/clientevents/defaultcs.aspx
The validator should trigger when the button is pressed, if it is not set CausesValidation="True" and maybe consider a RequiredFieldValidator to ensure it is populated before postback.
I have a textbox and a button, on button's clientClick I call javascript function and there is also server side coding.
Problem is, the page gets post back even if I have return False in the javascript.
Here is my javascript function:
function checkALphaNumericFormat(str) {
//get previous value before editing
var txtUserId = document.getElementById('<%=txtUserId.ClientID%>');
var userId = txtUserId.value;
var patternAlphaNumeric = /^[A-z0-9]+$/gi;
var match = userId.match(patternAlphaNumeric);
//Check Null values
if (txtUserId.value != null && txtUserId.value != "") {
//Check for AlphaNumeric values for User Id
if (match == null) {
alert("Please provide valid AlphaNumeric User Id");
return false ;
}
return false ;
}
else {
alert("User Id field should not be null");
return false ;
}
return false ;
}
and I am calling this function on my Form as:
<asp:Button runat="server" ID="btnCreate" CssClass="loginButton" style="margin:0px 0px 1px 30px;" OnClientClick ="return checkALphaNumericFormat(this.value);" Text="CREATE" />
Try to call JavaScript function as below:
OnClientClick="if(!validateform()){return false;}
where validateform() should be your java script function. Your java script function should have return = true; at the end of function in successfull execution, like in below function:
function validateform()
{
var txtSearch = document.getElementById('<%=txtKeywordSearch.ClientID%>')
if(txtSearch.value == '')
{
alert('No Search Creatria Selected!');
return false;
}
return true;
}
Please try and let me know if it works for you.
Thanks,
Harish