Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Templates - Replace DIV content

So I'm using jQuery templates and have the following code working in my application:

@using (Html.BeginForm())
    {
        @Html.DropDownList("StateList",
                            Model.States,
                            "< Select >"
                            )

        <div id="designCenters"></div>

        <script id="designCenterTemplate" type="text/html">
            <p><li>${Name}</li></p>
        </script>           
    }

    <script language="javascript" type="text/javascript">
        $("#StateList").change(function () {
            $.getJSON("/api/designcentersbystate/" + $(this).val(), 
              function (data) { 
                  $("#designCenterTemplate").tmpl(data).appendTo("#designCenters")
               });
        });
    </script>

Since I'm calling .appendTo in the callback function parameter of the template function, obviously the list of design centers is added to the list. My goal is to REPLACE the content within <div id="designCenters"> with the templated results.

Looking for the most efficient way to do this.

Thanks.

like image 722
Scott Avatar asked Feb 03 '11 17:02

Scott


People also ask

How to replace div content in jQuery?

For replacing innerHTML of a div with jquery, html() function is used. After loading the web page, on clicking the button content inside the div will be replaced by the content given inside the html() function.

How do I change the content of a div?

Use the textContent property to change the text of a div element, e.g. div. textContent = 'Replacement text' . The textContent property will set the text of the div to the provided string, replacing any of the existing content.

How to replace DOM element jQuery?

To replace a DOM element with the specified HTML or DOM elements using jQuery, use the replaceWith() method. The replaceWith (content) method replaces all matched elements with the specified HTML or DOM elements. This returns the JQuery element that was just replaced, which has been removed from the DOM.


2 Answers

Change the success function like so:

function (data) { 
    $("#designCenters").html($("#designCenterTemplate").tmpl(data))
}

Or you could empty the container each time.

$("#designCenters").empty();
$("#designCenterTemplate").tmpl(data).appendTo("#designCenters");
like image 177
Josiah Ruddell Avatar answered Dec 07 '22 18:12

Josiah Ruddell


You can replace the html in an element like this:

$("#designCenters").html(YOUR HTML HERE);
like image 44
stephen776 Avatar answered Dec 07 '22 18:12

stephen776