开发者

Javascript Box to appear when any form fields have been edited

I have a form that has various fields to save to a database. How do I make an alert box appear if any of those fields have been edited?

Just to be sure, t开发者_运维知识库he alert box CANNOT open up IF the fields have not been touched.


create a flag, eg:

var formUpdated = false:

wire up an OnBlur or OnChange (depending on the type of form element, like textbox or checkbox) event to every form field

document.getElementById('#formelementId').onChange = function () {
    // check if the value has changed
    formUpdated = true;
}

wire up an event to the onsubmit of the form e.g:

  document.forms[0].onsubmit = function () { 
      if(formUpdated){
         alert('the form was updated')
      }
  }


you can try reading up on onchange or onblur


Try the OnChange event.

following is simple example,

<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>


We eventually found the solution.

Insert into the head:

<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>

Then within the body, the form looks like this:

<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>&nbsp;
        </p>
</form>

We have to ensure that all fields that are applicable for that confirm box to appear must have the onchange answer of setDirtyFlag();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜