Warrio
Warrio

Reputation: 1913

show errors using JavaScript

I want to highlight a list of input received in an array and give the focus to the first of them.

<head>
<script type='text/javascript' src='app.js'></script>
</head>
<body>
  ...
  <script>showErrors(['firstName', 'lastName'])</script>
</body>

in app.js, I put the following javascript code:

function showErrors($fields)
{
    $fields.forEach(function($field){
        console.log($field);
        $('#'+$field).addClass('error-custom');
        $('#'+$field).css('border', 'red solid 2px');
    });

    //set focus to first field
    if($fields.length > 0)
    {
        $('#'+$fields[0]).focus();
    }
}

The JS code is executed but before the page is rendered. I tried to put the function showErrors into $(document).ready(function(){...} but it still had no effect.

Where should I place the code so I can have apply after the page is rendered?

Upvotes: 0

Views: 114

Answers (2)

Warrio
Warrio

Reputation: 1913

my errors was that I called the javascript function showError before rendering the input fields which were after.

I simply moved the call at the end of the page.

Upvotes: 0

pottedmeat7
pottedmeat7

Reputation: 78

looks like it works with $(document).ready(function(){ } ... don't know why you are pre-pending $ to your fields variable though it does nothing this isn't php ;)

function showErrors($fields)
{
	$fields.forEach(function($field){
		console.log($field);
		$('#'+$field).addClass('error-custom');
		$('#'+$field).css('border', 'red solid 2px');
	});
	
	//set focus to first field
	if($fields.length > 0)
	{
		$('#'+$fields[0]).focus();
	}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<script type='text/javascript' src='app.js'></script>
</head>
<body>
  <input type="text" id="firstName"/>
  <input type="text" id="lastName" />
  <script>$(document).ready(function(){showErrors(['firstName', 'lastName']);});</script>
</body>

Upvotes: 1

Related Questions