开发者

Where should I put my Javascript code in a ColdFusion model glue view?

Let's say I have a ColdFusion Model Glue view called login.cfm. In it, I have a form:

<form id="loginForm" action="#event.linkTo("user.login")#" method="POST">
    E-mail: <input id="emailField" type="text" name="email">
    Password: <input id="passwordField" type="text" name="password">
    <input type="submit开发者_如何学编程" value="Login">
</form>

Now I want to add in some Javascript validation for when the user clicks the Login button. Something like this in jQuery:

<script type="text/javascript">
    $(function() {
        $('#loginForm').submit(function() {
            // check that emailField is not empty and is a valid e-mail
            // check that passwordField is not empty
            // if validation fails, add in DOM elements to show error messages
        });
    });
</script>

Where should I be adding this Javascript code? Do I stick it directly into the login.cfm view? Or is there a better way of handling this? Preferably, I'd like to stick my Javascript code from all my views to the bottom of the body.


There are a quite a few different strategies for this. The easiest is it put your view-specific script in a single .js file and include it through a <script src="path"></script> tag just before closing the <body> tag.

You can also look at libraries such as require.js that allow you to asynchronously load script files and their dependencies.


You could just leave that in the view file the way it is.

I am not a big fan of having <script> blocks all over the place though, so I typically will use <cfsavecontent> and <cfhtmlhead> to make sure all these blocks of JS wind up in the <head>

You could do this right in the login.cfm file.

<cfsavecontent variable="js">
<script type="text/javascript">
    $(function() {
        $('#loginForm').submit(function() {
            // check that emailField is not empty and is a valid e-mail
            // check that passwordField is not empty
            // if validation fails, add in DOM elements to show error messages
        });
    });
</script>
</cfsavecontent>
<cfhtmlhead text="#js#" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜