I apologize for the noob question, I just do not know yet JS (I am learning java).

I have a form:

<form onsubmit="return checkForm(this)"action="/search" method="POST"> <div id="fields_container"> <div> <div class="element">First name:</div> <input id="name" type="text" name="" placeholder="James" /> <span id="err_name" class="error"></span> </div> <div> <div class="element">Email:</div> <input id="email" type="text" name="" placeholder="example@email.com" /> <span id="err_email" class="error"></span> </div> </div><!-- #fields_container> --> <div> <input type="submit" value="Submit"> </div> </form> 

and there is a script that I specify in the head

 < script type = "text/javascript" > function checkForm(form) { valid = true; if (document.getElementById('name').value.replace(/^\s*/, '').replace(/\s*$/, '') == "") { document.getElementById('err_name').innerHTML = 'Enter your first name'; valid = false; } else { document.getElementById('err_name').innerHTML = ''; }; pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([az]{2,6}(?:\.[az]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i); emailAddress = document.getElementById('email').value; if (emailAddress == "") { document.getElementById('err_email').innerHTML = 'Enter your email'; valid = false; } else if (!pattern.test(emailAddress)) { document.getElementById('err_email').innerHTML = 'Wrong email, please correct this field'; } else { document.getElementById('err_email').innerHTML = ''; }; return valid; }; < /script> 

those. when you click on the "submit" button, the correctness of the form is checked. How can I put this script into a separate file and how to correctly register it for execution on the html page?

  • one
    Paste the contents of the script tag into your .js file, without the tag itself, where the script was previously tagged with the code will be <script src = "path to your file-script.js"> </ script> - Duck Learns to Hide

1 answer 1

 <script src="main.js" type="text/javascript"></script> 

Pre-move the code to the main.js file (only the code, without the <script> ) and of course create it. It turns out when you prescribe this script, the contents of main.js is substituted.

PS you can write without type="text/javascript"

  • Strangely, before that, it seemed to be doing the same thing, but it didn’t work, now everything works fine (it’s obvious that I’ve been stupid). Thank! - uncleSAM
  • @uncleSAM The most common reasons for "not even working" are 1). Incorrectly written path to the file with the script. 2). Single self-closing tag <script src = "path" /> - does not work. - Duck Learns to Hide
  • @ Duck LEARNING TAKE NOTE. Thank. - uncleSAM