2

How can I solve this error:

Uncaught TypeError: Object has no method 'appendTo' in the following code :

    function refresh(){
        $('#contacts').empty();
        $( "#contactTmpl" ).tmpl( {contacts:contacts} ).appendTo( "#contacts" );
        $( ".contact" ).each( function(i) {
            var contact = contacts[i];
            $( "input.tomap", this ).link( contact );
        });
    }


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

<form>
    <div id="contacts">Loading ...</div>
    <button class="add">New</button>
    <button class="save"> Save</button>
</form>
<script id="contactTmpl" type="text/x-jquery-tmpl">

    {{each contacts}}
        <div class="contact" data-index="${$index}">
            <label>First name</label> <input class="tomap" name="firstName" value="${firstName}">
            <label>Last name</label> <input class="tomap" name="lastName" value="${lastName}">
            <label>Number</label> <input class="tomap" name="phone" value="${phone}">
            <div class="tools">
                <button class="delete"</button>
            </div>
        </div>
    {{/each}}
</script>

this is the html and javascript code

1
  • There's nothing obviously wrong with what you've included here. WHen is refresh() getting called? After document ready or load, I hope. What is inside a.js? Maybe you could throw up a fiddle to look at?
    – Kato
    Nov 3, 2011 at 21:42

2 Answers 2

4

I going to assume you are using jQuery templates, since that is what it looks like. If the template fails to render then it returns null which I believe is why you are getting the object has no method error. I trimmed your code down to just the template and the call to render the template and fixed the {{each}} and the ${$index}. I also assume the variable contacts is an array of objects.

A working fiddle is here: http://jsfiddle.net/brettwp/yfcuL/

Also the code:

<div id="contacts">EMPTY</div>
<script id="contactTmpl" type="text/x-jquery-tmpl">
    {{each(index,contact) contacts}}       
        <div class="contact" data-index="${index}">
            <label>First name</label> <input class="tomap" name="firstName" value="${contact.firstName}">
            <label>Last name</label> <input class="tomap" name="lastName" value="${contact.lastName}">
            <label>Number</label> <input class="tomap" name="phone" value="${contact.phone}">
            <div class="tools">
                <button class="delete"></button>
            </div>
        </div>
    {{/each}}
</script>

$(function(){
    $( "#contactTmpl" ).tmpl( {contacts: contacts} ).appendTo( "#contacts" );
});
1

You need to create the node first. Try this:

$('<div id="contactTmpl"/>').tmpl( {contacts:contacts} ).appendTo( "#contacts" );
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.