我有几个仅包含日期的文本框。如果一个文本框有日期,并且用户尝试提交而不在另一日期文本框中输入日期,则他们将在提交之前停止。我想要执行此操作的方法是使用以下 javascript 函数:
function ClientValidate(sender, args) {
// Get Both form fields
var txtdate1 = document.getElementById('<%=txtdate1.ClientID%>');
var txtdate2 = document.getElementById('<%=txtdate2.ClientID %>');
// do you client side check to make sure they have something
if (txtdate1.value != '' && txtdate2.value == '') {
args.IsValid = false;
}
else
{
args.IsValid = true;
}
if (txtdate2.value != '' && txtdate1.value == '') {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
文本框和日期内容的创建如下。
Dim bttndate1 As New ImageButton
bttndate1.ID = "bttndate1"
Dim txtdate1 As New TextBox
txtdate1.ID = "txtdate1"
txtdate1.Width = 65
Dim calex1 As New AjaxControlToolkit.CalendarExtender
calex1.TargetControlID = "txtdate1"
calex1.Format = "MM/dd/yyyy"
calex1.PopupButtonID = "bttndate1"
'**************** date box2 ***************
Dim bttndate2 As New ImageButton
bttndate2.ID = "bttndate2"
bttndate2.Style.Add("cursor", "pointer")
Dim txtdate2 As New TextBox
txtdate2.ID = "txtdate2"
txtdate2.Width = 65
Dim calex2 As New AjaxControlToolkit.CalendarExtender
calex2.TargetControlID = "txtdate2"
calex2.Format = "MM/dd/yyyy"
calex2.PopupButtonID = "bttndate2"
这是验证器
Dim custval As New CustomValidator
custval.ID = "ValidPage"
custval.ClientValidationFunction = "ClientValidate"
custval.ErrorMessage = "You Must Enter a 'From' Date and a 'To' Date"
custval.ErrorMessage = "You Must Select a Vendor"
custval.SetFocusOnError = True
custval.ControlToValidate = "txtdate1"
custval.EnableClientScript = True
我的问题是 JavaScript 找不到这两个文本框,因为我在代码中创建了它们 有什么想法吗?
最佳答案
我是 ClientScriptManager 的反对者。上面的解决方案可能会起作用,但另一种方法是在 ClientValidate() 方法之外在 JavaScript 中声明几个变量。
var textdate1;
var textdate2;
在页面中的某个位置放置一个文字(只要它具有 runat="server"属性,您就可以将其放置在任何地方)。
<asp:Literal ID="litJSVars" runat="server" />
然后,如果您要创建文本框等内容,请添加以下代码:
this.litJSVars.Text = "textdate1 = document.getElementById('" + txtdate1.ClientID + "');\\n";
this.litJSVars.Text += "textdate2 = document.getElementById('" + txtdate2.ClientID + "');";
它并不比上面的想法更好或更坏,只是实现方式不同而已。
关于c# - 在 JavaScript 中获取控制权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1263185/