How to show an alert instead of highlighting the field?

Hi,

I am using the following style of web form in which I use “required” so that users cannot submit form without filling up all the required fields. It works fine, but my form is a bit bigger and in mobile view if a user leaves a field or two empty and they press the submit buttons, it looks like that the form is not working , becuase browser is highlighting the field but not actually scrolling the page to that field which is creating confusion.

Is there any way to display a simple alert box message incase a “required” field is missing or atleast auto scroll to that field so user knows that they have to fill up that field ??

I am looking for a common solution that just checks if any field with “required” parameter not filled then either show alter box message or auto scroll to that field, so user knows they have to fill that field up.

The “required” i am refering to is this:

[code]

[/code]

Any help is appreciated.

Thanks.

I think the scroll position could be added to the javascript.

To have CSS to show an alert with e.g. a link to the missing entry you need the assistance of the javascript anyway.

I’ll alert the moderators to move the topic to the Javascript section.

Moved to JS category per Erik_J.

1 Like

Hi there Tapan,

try this example…

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>untitled document</title>

<!--<link rel="stylesheet" href="screen.css" media="screen">-->

<style media="screen">
#demo div  {
    margin: 1em 0;
 }
input[type="submit"] {
    margin-top: 50em;
 }
</style>

</head>
<body> 
<form id="demo" action="demo_form.asp" method="post">
<div>
  <label for="opt0">optional: </label>
  <input type="text" id="opt0" name="opt0">
</div><div>
  <label for="fname">first name: </label>
  <input type="text" id="fname" name="fname" required>
</div><div>
  <label for="opt1">optional one: </label>
  <input type="text" id="opt1" name="opt1 ">
</div><div>
  <label for="sname">surname: </label>
  <input type="text" id="sname" name="sname" required>
</div>
  <input type="submit" id="button" value="Submit">
</form>

<script>
(function() {
   'use strict';
   var inp=document.getElementById('demo').getElementsByTagName('input');
   document.getElementById('button').addEventListener('click',function(){return check();},false);
function check(){
for(var c=0;c<inp.length;c++) {
if((inp[c].value==='')&&(inp[c].required===true)){
   location.href='#'+inp[c].name;
   }
  }
 }
}());
</script>

</body>
</html>

Note that I have pushed the submit button
down a long way to simulate scrolling. :sunglasses:

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.