A guide to swapping text in a jQuery DOM component

In order to construct HTML from a jQuery ajax response, I prefer not to nest unsightly strings in javascript and avoid using templating scripts like mustache. Instead, I decided to utilize a template HTML with display: none as shown below:

<div id="message-template" class="message-tile" style="display: none;">
    <div class="profile-thumb"><img src="{{thumb-url}}" width="48" height="48" alt="{{person-name}}" /></div>
    <div class="message-data">
        <div class="message-info">
            <div class="sender-name">
                <a href="{{person-url}}">{{person-name}}</a>
            </div>
            <div class="posted-to">
                To <a href="{{posted-to-url}}">{{posted-to-title}}</a>
            </div>
        </div>
        <div>{{message-body}}</div>
    </div>
</div>

My goal is to replace the strings between {{ }} with the actual values obtained from the JSON object. Consider the following function that is invoked during the onSuccess event of the jQuery.ajax:

function createNewElement(jsonObj) {
    var $clone = $('#message-template').clone();
    $clone.replaceString("{{person-name}}", jsonObj.personName);
    $clone.replaceString("{{thumb-url}}", jsonObj.thumbUrl);
    $clone.replaceString("{{person-url}}", jsonObj.personUrl);
    // etc
    $("#target-container").append($clone);
}

I introduced the replaceString method, but is there an alternative approach? Or would I need to iterate through each child element using find()?

Answer №1

Did you know that it is possible to create your own templates without rendering them on your web page? One way to achieve this is by using the

<script type = "text/template">
tag:

<script id="custom-template" type = "text/template">

    <div class="custom-tile" style="display: none;">
        <div class="profile"><img src="{{image-url}}" width="48" height="48" alt="{{person-name}}" /></div>
        <div class="data">
            <div class="info">
                <div class="name">
                    <a href="{{url}}">{{person-name}}</a>
                </div>
                <div class="posted-to">
                    To <a href="{{post-url}}">{{post-title}}</a>
                </div>
            </div>
            <div>{{message-text}}</div>
        </div>
    </div>

</script>

You can then easily substitute values into the template like this:

function insertNewElement(dataObj) {
    var $content = $('#custom-template').html();
    $content = $content.replace("{{person-name}}", dataObj.name)
                       .replace("{{image-url}}", dataObj.imageUrl)
                       .replace("{{url}}", dataObj.url);
    // etc
    $("#target-elem").append($content);
}

Answer №2

The utilization of the replace() method can greatly enhance the flexibility of regex.

An example implementation is as follows:

html.replace(/\{\{([^}]+)\}\}/g, function(all, key) {                   
                return jsonObj[key] || all;
            });

This ensures that {{personName}} retrieves its corresponding value from jsonObj.personName.

Answer №3

function createCustomElement(dataObj) {
    var $copy = $('#template-container').clone();
    $copy.html($copy.html().replace("{{name}}", dataObj.name));
    $copy.html($copy.html().replace("{{image-url}}", dataObj.imageUrl));
    $copy.html($copy.html().replace("{{profile-url}}", dataObj.profileUrl));
    // add more functionality here
    $("#custom-target").append($copy);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Function that contains a JavaScript reference and observation

I'm experiencing issues with the code below and I'm having trouble figuring out what's causing the problem. function some(){ for (var i=0;i<....;i++) { var oneObject; ...some logic where this object is set oneObject.watch(prop ...

jQuery replacing spaces in id names

I'm encountering an issue with the following HTML and jQuery code. The problem seems to be related to the space in the ID name. HTML <span id="plus one">Plus One</span> jQuery $("#plus one").hide(); Since I'm unable to change the ...

Obtain JSON information and integrate it into an HTML document with the help of

I am currently working on a PHP/JSON file named users-json.php. <?php include_once('../functions.php'); if (!empty($_GET['id'])) { $GetID = $_GET['id']; $query = "SELECT Username, Firstname WHERE UserID = :ID"; $stmt = $d ...

Share JSON data across functions by calling a function

I am currently working on a project where I need to load JSON using a JavaScript function and then make the loaded JSON objects accessible to other functions in the same namespace. However, I have encountered some difficulties in achieving this. Even after ...

Error: Unable to assign value to the innerHTML property of an undefined element created by JavaScript

When designing my html form, I encountered an issue where I needed to display a message beneath blank fields when users did not fill them out. Initially, I used empty spans in the html code to hold potential error messages, which worked well. However, I de ...

Troubleshooting issues with rowspan in a Datatable

I am currently utilizing jQuery DataTables to display my grid data and implementing the rowspan concept with the rowsGroup option. Initially, it works well by spanning some rows and looking visually pleasing, but eventually, it starts failing. Here are so ...

How can I place an Object in front of an Array in JavaScript?

Currently, I am working on an Angular project where I need to modify a JSON array in order to display it as a tree structure. To achieve this, the objects in the array must be nested within another object. Desired format / output: this.nodes = [ { id ...

There is an issue as headers cannot be changed after being set for the client

I am in the process of developing an employee leave management system. Everything runs smoothly until an issue arises when attempting to update the leave status as an admin, and the logged-in account or user does not have admin privileges. There is a midd ...

Highcharts: single point muted and not easily seen when markers are turned off

Highchart displaying data with some null points (only visible via tooltip if marker disabled): https://i.stack.imgur.com/u04v1.png https://i.stack.imgur.com/uRtob.png Enabling markers will resolve the issue of invisible points, but it may look cluttered ...

Scroll Bar Menu (User-Controlled)

I'm looking for any libraries out there that can replicate or provide a similar horizontal scrolling menu to that of espn.com's homepage. I'm relatively new to jquery and feeling a bit lost on where to begin. I did some searching on Google, ...

JavaScript: Utilize MooTools to extract a string containing a specific class and then pass it through a parent function

I am facing a major issue and struggling to find a solution for it. My problem involves returning values, mostly strings, that I can utilize in various contexts. For instance, I need to verify whether something is 0 or 1 in an if/else statement, or insert ...

The dynamically created array length is indicating as null

Although this question has been asked numerous times, most answers are in plain JavaScript. I have a function that generates an array with product data. This array is then utilized in another function to retrieve new data via JSON. $(function(){ var p ...

How to Prevent Annoying Flickering of Jquery toggle() in Safari

Having some issues with a basic toggle effect in Safari. There's an irritating flicker at the end of the hide animation. Any suggestions? CSS #menu { position:absolute; left: 30px; top: 30px; padding: 30px; background: #FF0; } # ...

Issue: The function view.hlp(...) is not recognized within jsrender

Currently, I am utilizing jsrender to map the templates within a grid. In this process, I have incorporated a method call inside jsrender based on a certain condition as shown below: @section scripts{ $.views.helpers({ isMobile: function () { ...

The right column in a relatively positioned layout descends as an element in the left column is revealed

Currently in the process of constructing a registration form for our website, everything is going smoothly with one minor hiccup. The form consists of two columns where users enter their information. Initially, when designing elements for the first (left) ...

jquery dialog box displaying a webpage

I am looking to implement a feature where, upon clicking the edit link in the last column of my dataTable, a separate page for editing should open within a jQuery dialog box. The goal is to seamlessly submit data while providing a user-friendly experienc ...

AJAX - Implementing a delay in displaying AJAX results

My search function uses AJAX to retrieve data from the web-server, and I am trying to implement a fade-in animation for each search result. I want the results to load and fade in one by one with a slight delay between them. Currently, it seems like all th ...

Modify the h:outputText value dynamically with the power of jQuery!

Is it possible to use jQuery to dynamically change the value of my OutputText component? This is the code snippet for my component: <h:outputText id="txt_pay_days" value="0" binding="#{Attendance_Calculation.txt_pay_days}"/> I would apprecia ...

What steps are involved in setting up a RESTful service for a web application?

After extensive searching, I'm still unclear on how to approach the question posed in the title. The concept of RESTful was introduced to me just this morning, and the more I delve into it, the more puzzled I become. A few weeks back, I undertook the ...

"Enhance your forms with Ajax for seamless uploading and convenient text

My current challenge involves submitting a form that features multiple file uploads using ajax along with text input. I'm facing an issue where if a user successfully uploads all the files using ajax but forgets to enter their name, the form resets an ...