Amer Enaya
Amer Enaya

Reputation: 25

How can i solve a "no method 'appendTo' error?

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

Upvotes: 2

Views: 3855

Answers (2)

Brett Pontarelli
Brett Pontarelli

Reputation: 1728

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" );
});

Upvotes: 4

SeanCannon
SeanCannon

Reputation: 78006

You need to create the node first. Try this:

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

Upvotes: 1

Related Questions