Using jQuery inside an ejs template

So I'm building an express Parse BaaS app and want to show the Bootstrap modality depending on whether the error message is passed to the view. I am trying to do this using simple .modal ("show") code from bootstrap. This template has a partial part that includes a link to jQuery and bootstrap js. However, this pattern breaks off by saying $ is undefined when it runs. Here's the inline js.

<div class="modal-body">
                  <% if(registerError) { %>
                    <div class="error"><%= registerError %></div>
                      <% $('#registerModal').modal('show') %>   
                  <% } %>
                <form class="form-inline login-form" method='post' action='/signup'>
                  <div class="error bg-danger" style="display:none"></div>
                  <input type="email" id="register-username" name="registerEmail" class="form-control" placeholder="Email" />
                  <button type="submit" id="login" class="btn btn-primary">Next</button>
                </form>

              </div>

      

When I exit the modal call, the template displays the error correctly, but it requires me to manually navigate to the modal. I want this modal to be displayed when the template is loaded if there is an error. I'm new to ejs and am expressing in general, so I'm not sure where the jquery call should live.

+3


source to share


2 answers


The reason this code doesn't work is because you are trying to run JS client side server side (i.e. internally <% %>

). It should work if you put the expression $

in a script tag.



<% if(registerError) { %>
    <div class="error"><%= registerError %></div>
    <script type='text/javascript'>$('#registerModal').modal('show');</script>   
<% } %>

      

+4


source


In sails / ejs I had to do

<script>
    window.onload = function () {
        $('#registerModal').modal('show');
    }
</script>

      



Otherwise, JQuery has not been loaded yet when $ () is called.

0


source







All Articles