我正在验证来自javascript的表单。 目标是:如果用户未在必填字段中输入值,则会显示错误消息,并在几秒钟后消失。 但 问题是:错误消息没有显示,这可能是因为从javascript我无法在标签控件中写入错误消息。但是,如果我使用javascript警报而不是显示标签,它的工作原理。
代码: 的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其他东西
<asp:ImageButton ID="iBtnSave" runat="server" ImageUrl="~/images/createOffer.png"
onclick="iBtnSave_Click" OnClientClick="return validateRequiredField()" />
并在
背后的代码中protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
iBtnSave.Attributes.Add("onclick", "return validateRequiredField()");
//some other stuff
}}
如果有人能帮助我找到我的错误会很好.. 欢呼声
答案 0 :(得分:1)
混合使用jQuery和IE-Only JScript。
确保仅使用jQuery或跨浏览器JavaScript
更改
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;
}
到
$("#<%=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");
}
});