Skip to content Skip to sidebar Skip to footer

Prompt Keeps Coming Up

i have calculation form i want to put empty validation check on each textbox. but the problem is alert box does not close after checking first box.i want to check 10 fields before

Solution 1:

You've got a vicious cycle of events that lead back to each other, so every time you clear your propmt, a new one is generated. Whenever the user leaves a field and you detect that it is invalid, you set the focus back to it, causing whatever field the user just moved to to lose its focus, causing another validation error.

Additionally, you've now found out why alert() and prompt() can be evil since they block the UI.

A better approach would be to have a message appear in a DOM element next to the field. This won't block the UI.

... And, don't use in line HTML event handling attributes (onclick, onmouseover, etc.). Use dedicated JavaScript with .addEventListener(). Here's why.

// Place this code in a <script> element, just before </body>// Get references to any HTML elements you'll need to work withvar txt1 = document.getElementById("txt1");
var txt2 = document.getElementById("txt2");

// Set up event handling functions here, not in the HTML
txt1.addEventListener("blur", validate);
txt1.addEventListener("input", validate);
txt2.addEventListener("blur", validate);
txt2.addEventListener("input", validate);

// This one function is called when either field is having input entered // or when the user leaves either field.functionvalidate(evt) {
  // All event handling functions are automatically passed a reference to the// event that they are handling (evt here). From that object, we can get a // reference to the object that triggered the event (evt.target here).// Lastly, always call the .trim() string method on user input. It strips// any leading or trailing spaces off of the inputted value (a common user mistake).var val = evt.target.value.trim();
  
  var message = ""; // This will hold any error message we wish to show// Begin validationsif(val === ""){
    message = "Can't be empty!";
  } elseif(isNaN(parseInt(val,10))){
    message = "Not a number!"
  }
  
  // Place the error message in the element that comes just after the invalid field
  evt.target.nextElementSibling.textContent = message
}
span.error { color:red; }
<!-- Note the empty span elements just after each field... --><inputtype="text"id="txt1"name="Rate"autofocus><spanclass="error"></span><inputtype="number"id="txt2"name="1"required><spanclass="error"></span>

Post a Comment for "Prompt Keeps Coming Up"