3

I have a javascript function that has been driving me nuts. This is the latest variation on the problem. If I put the code in line after the end of the form (i.e. after the tag, the code works just fine; but if I put a script reference to the code, it loads but doesn't execute.

This works:

<script type="text/javascript">
    var matchFieldName = 'dotmatch';
    var resultFieldName = 'dotnumber';
    var lookupURL = "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind";
    var labelFieldName = "JobTitle";
    var valueFieldName = "DOTNumber";
    $('#' + matchFieldName).autocomplete({
        source: function(request, response) {
            $.ajax({
                type: "POST",
                url: lookupURL,
                contentType: 'application/json',
                dataType: "json",
                data: JSON.stringify({ prefixText: request.term, count: 20 }),
                success: function(data) {
                    var output = jQuery.parseJSON(data.d);
                    //                        var output = eval(data.d);
                    response($.map(output, function(item) {
                        var lbl = "item." + labelFieldName + " (item." + valueFieldName + ")";
                        var val = "item." + valueFieldName;
                        return {
                            //                                label: lbl,
                            //                                value: val
                            //                                label: eval('item.' + lableFieldName + '(item.' + valueFieldName + ')'),
                            //                                value: eval('item.' + valueFieldName)
                            label: item.JobTitle + "( " + item.DOTNumber + ")",
                            value: item.DOTNumber
                        }
                    }));
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus);
                }
            });
        },
        minLength: 2,
        select: function(event, ui) {
            $('#' + resultFieldName).val(ui.item.value);
            return ui.item.label;
        }
    });
</script>

</div>

But this doesn't:

</form>
    <div>

<script type="text/javascript" src="js/DOTAutocomplete.js" />

    </div>
</body>

The only contents of the .js file are the lines that work.

ARGH!!!

0

4 Answers 4

10

Self-closing <script> tags aren't valid, this:

<script type="text/javascript" src="js/DOTAutocomplete.js" />

should be:

<script type="text/javascript" src="js/DOTAutocomplete.js"></script>

Also note that since you're using a selector $('#' + matchFieldName), the file should either be included after that element is present, or wrap your code in a document.ready handler, for example:

$(function() {
  //your code...
});
Sign up to request clarification or add additional context in comments.

2 Comments

YES! Thank you, Nick. You nailed it. I made both changes and it work.
1

Chances are that you're not targeting the file correctly. You're using type="text/javascript", right? If it works inline but not with a src reference, it's almost certainly that you're not nailing the path to the file.

4 Comments

Oh, I see it now, Nick's nailed it. I either skipped the src= code or else it wasn't posted yet.
This answer did solve my "file_tree is not a function" and "lightSlider is not a function. But, only partially. I did find that my paths were wrong. Once I made the corrections, my library functions worked. But the solution isn't perfect. I had to put my script lines near the bottom of my html. Putting the exact same scripts in the head didn't work, "...is not a function" happens again. What is being overlooked here and the other answers is that successive scripts, especially the libraries relying on jQuery, seem to step on each other in unpredictable ways (guessing duplicate function names).
As @Nick Craver pointed out, jQuery code should nearly always be wrapped in a document ready block. This ensures that the important page assets have loaded before script execution. This lets you put your scripts and references in the head (where they should be) without worry about timing.
Yes, but even when my "jQuery widget" calls (file tree, lightSlider, etc) are wrapped in $(document).ready(function(){ ... call function here }) they don't work. The only difference between whether they work or don't work is where I place the <script src=""></script> in the document. When that happens, I suspect these libraries are overwriting functions or function names.
1

Try this, put this code back into an external file, make sure you have a valid script include tag, per Nick's post.

$(function(){
    var matchFieldName = 'dotmatch'; 
    var resultFieldName = 'dotnumber'; 
    var lookupURL = "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind"; 
    var labelFieldName = "JobTitle"; 
    var valueFieldName = "DOTNumber"; 
    $('#' + matchFieldName).autocomplete({ 
        source: function(request, response) { 
            $.ajax({ 
                type: "POST", 
                url: lookupURL, 
                contentType: 'application/json', 
                dataType: "json", 
                data: JSON.stringify({ prefixText: request.term, count: 20 }), 
                success: function(data) { 
                    var output = jQuery.parseJSON(data.d); 
                    //                        var output = eval(data.d); 
                    response($.map(output, function(item) { 
                        var lbl = "item." + labelFieldName + " (item." + valueFieldName + ")"; 
                        var val = "item." + valueFieldName; 
                        return { 
                            //                                label: lbl, 
                            //                                value: val 
                            //                                label: eval('item.' + lableFieldName + '(item.' + valueFieldName + ')'), 
                            //                                value: eval('item.' + valueFieldName) 
                            label: item.JobTitle + "( " + item.DOTNumber + ")", 
                            value: item.DOTNumber 
                        } 
                    })); 
                }, 
                error: function(XMLHttpRequest, textStatus, errorThrown) { 
                    alert(textStatus); 
                } 
            }); 
        }, 
        minLength: 2, 
        select: function(event, ui) { 
            $('#' + resultFieldName).val(ui.item.value); 
            return ui.item.label; 
        } 
    }); 
}); 

3 Comments

this will make sure the DOM has loaded prior to executing this code. the problem you were likely having is code was executing before the elements involved had actually be integrated into the DOM.
you shouldn't have <script> tags inside a JavaScript function :)
yeah... copy and paste error. Fixed: Updated, since scripts tags shouldn't be in an external js include at all, despite my obvious mistake of sticking a script tag on line 2.
0

As noted above by Mr. Craver, self-closing Javascript tags are no good. Here's a discussion on why:

Why don't self-closing script tags work?

There's no satisfying reason why - it's just that the SCRIPT tag isn't marked as having a content model of EMPTY in the spec - probably because the src attribute was added later.

2 Comments

There is a good reason. Elements that have, or have the ability to have, inner-text use a closing tag, elements that cannot have inner text should be a single element. An img or an input are single tags, a div or a script use closing tags.
I understand that that's the case, but I don't consider that a good reason. The spec should support both configurations - it's perfectly clear semantically what I intend when I use a self-closing JS tag...that's why this problem crops up so often.<br /><br />The essential problem is that you can't do it both ways, and you should be able to. The limitation is a technical, not a logical one.

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.