0

(I'm new to HTML/JS). I'm trying to clean up my HTML file to bear-bone markup and put all logic in a .js file, including the CDN inclusions. I'm aware of How to include CDN in javascript file (*.js)?

In the HTML below, I tried to move the 2 'src' lines at the bottom, to form_validation.js, also shown below. But when I do that, the Semantic UI form validation stops working and I get error messages that .form is not a function etc. That addCDN() call in the JS file doesn't do it.

I imagine this has to do with me not understanding the order in which these things are processed by the browser... I would greatly appreciate some education.

<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
    <style>.container {margin: 15em;}</style>
</head>
<body>
    <div class="container">
    <form class="ui form">
        <p>Give this a try:</p>
        <div class="field">
            <label>Name</label>
            <input placeholder="Your Name?" name="name" type="text">
        </div>
        <div class="ui submit button">Submit</div>
        <div class="ui error message"></div>
    </form>
    </div>

    <!-- get these guys out-a-here -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>
    <!-- ..... -->

    <script src="form_validation.js"></script>
</body>
</html>

/*
 * form_validation.js
 * Uses Semantic UI validation JSON
 */

function addCDN(){
    // Can be removed? Ideally not in the HTML file...
    var jq = document.createElement('script');
    jq.setAttribute('src',
        'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'
    );  
        document.head.appendChild(jq);

    var sui = document.createElement('script');
    sui.setAttribute('src',
        'https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js'
    );  
        document.head.appendChild(sui);
}

$(document).ready(function(){
    addCDN();   // this doesn't seem to happen :(
    $('.ui.form').form({
            fields: {name : ['minLength[6]', 'empty']}
        }); 
});```
Yanay Lehavi
  • 166
  • 11

0 Answers0