简体   繁体   中英

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?

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> 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM