Johnny Santana Johnny Santana - 3 months ago 11
Javascript Question

Call a JS function from and external file passing a parameter on page load

I'm kind of new to JS yet, so I'd like to know if there is anyway to do this:

main.js:

$(function () {
$('.delete_btn').click(function () {
var confirmation = confirm('Deseja remover este evento?');
if (!confirmation) return false;
})
})

function updateIsoDate(date) {
$('.datepicker').datepicker('setDate', date);
}


I'm already calling a function of it onload, but It doesn't required and specific thing.

events.ejs:

...

<div class="form-group">
<label for="date">Data do Evento</label>
<input type="text" class="form-control datepicker" id="date"name="date">
<input type="hidden" id="dateInfo" name="date" value=' <%= event.date %>'>
</div>


...

<script>
$(document).ready(function () {
updateIsoDate($('#dateInfo').val());
});
<script>


Can I call a function from a external file passing a parameter to it?
I don't know if I need to add scr="js/main.js" to my "script" tag cuz It's already previously loaded

So I'm trying to change my IsoDate format to display into my datepicker. It's working but I want to make the page a little cleaner calling it from another file.

Answer

events.ejs:

I've add the javascript file

<script src="/js/main.js"></script>

Here the input where the value is

    <div class="form-group">
      <label for="date">Data do Evento</label>
      <input type="text" class="form-control datepicker dp-add" id="date" name="date">
      <input type="hidden" id="dateInfo" name="date" value=' <%= event.date %>' required>
   </div>
    ...

Then used $(window).on('load', function() to pass the argument and call the function inside the main.js file

    <script>
    $(window).on('load', function() { 
        // Formating IsoDate to be displayed and setting into the datepicker
        updateIsoDate($('#dateInfo').val());
    });
    </script>

main.js:

function updateIsoDate(date) {
$('.datepicker').datepicker('setDate', date);
}