我有一个表单,其中包含要保存到数据库的各种字段。如果已编辑任何这些字段,如何显示警告框?
可以肯定的是,如果没有触摸字段,则警告框无法打开。
答案 0 :(得分:1)
创建一个标志,例如:
var formUpdated = false:
将OnBlur或OnChange(取决于表单元素的类型,如文本框或复选框)事件连接到每个表单字段
document.getElementById('#formelementId').onChange = function () {
// check if the value has changed
formUpdated = true;
}
将事件连接到表格的onsubmit,例如:
document.forms[0].onsubmit = function () {
if(formUpdated){
alert('the form was updated')
}
}
答案 1 :(得分:0)
您可以尝试阅读onchange
或onblur
答案 2 :(得分:0)
尝试OnChange事件。
以下是一个简单的例子,
<HTML>
<HEAD>
<TITLE>Example of onChange Event Handler</TITLE>
<SCRIPT>
function valid(input) {
alert("You have changed the value from 10 to " + input);
}
</SCRIPT>
</HEAD>
<BODY>
<H3>Example of onChange Event Handler</H3>
Try changing the value from 10 to something else:<BR>
<FORM>
<INPUT TYPE="text" VALUE="10" onChange="valid(this.value)">
</FORM>
</BODY>
</HTML>
答案 3 :(得分:0)
我们最终找到了解决方案。
插入头部:
<script language="javascript" type="text/javascript" >
var needToConfirm = false ;
function Submit_Click() {
needToConfirm = false;
}
function setDirtyFlag() {
needToConfirm = true; //Call this function if some changes is made to the web page and requires an alert
// Of-course you could call this is Keypress event of a text box or so...
}
window.onbeforeunload = confirmExit;
function confirmExit() {
if (needToConfirm)
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
</script>
然后在正文中,表单如下所示:
<form onunload="confirmExit()">
<p>
<input id="Text1" type="text" value ="jitesh" onchange="setDirtyFlag();" /></p>
<p>
<input id="Checkbox1" type="checkbox" checked="checked" onchange="setDirtyFlag();"/></p>
<p>
<input id="Radio1" checked="checked" name="R1" type="radio" value="V1" onchange="setDirtyFlag();" /></p>
<p>
<input id="Submit" type="button" value="Submit" onclick="Submit_Click();"/></p>
<p>
</p>
</form>
我们必须确保所有适用于该确认框的字段必须具有setDirtyFlag()的onchange答案;