0

This function works when I put it via inline html just before the end of </body>. But once I move it to js/main.js it doesn't work anymore.

Inline:

<script>
var rowNum = 0;
    function addRow(frm) {
        rowNum ++;
        var html = $('.addphone').html();
        jQuery('.phone_adds').append(html);
    }

    function removeRow(rnum) {
        jQuery('#rowNum'+rnum).remove();
    }
</script>

Versus external .js:

$(function() {

.....other functions...

    var rowNum = 0;
    function addRow(frm) {
        rowNum ++;
        var html = $('.addphone').html();
        jQuery('.phone_adds').append(html);
    }

    function removeRow(rnum) {
        jQuery('#rowNum'+rnum).remove();
    }

});

Error message: Uncaught ReferenceError: addRow is not defined

Help? What is wrong here?

2
  • how are you referencing the external js file in your page? Commented May 14, 2014 at 21:54
  • @KarthikGanesan with <script src="js/main.js"></script> before the end of </body> Commented May 14, 2014 at 21:58

1 Answer 1

2

You are enclosing your function into a wrapper:

$(function() {

    var rowNum = 0;
    function addRow(frm) {
        rowNum ++;
        var html = $('.addphone').html();
        jQuery('.phone_adds').append(html);
    }

    function removeRow(rnum) {
        jQuery('#rowNum'+rnum).remove();
    }
});

When you do that your defined functions are in fact subfunctions of the wrapper (the "$" function), so, when its called outside from this wrapper, the function doesnt exists.

The "inline" works because your function is global and visible anywhere (is not inside another function).

I would recommend removing the wrapper of the function definition and just leave the function call in the $() wrapper.

Sign up to request clarification or add additional context in comments.

1 Comment

The reasoning is correct; but I'd recommend removing the $(function() { (first line) and the closing }); (last line) to keep things simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.