Angel
Angel

Reputation: 21

How to pass variable to the JavaScript function within HTML?

My code works if it is hardcoded with LLC. However, I would like to pass the variable and do not know how to modify the code to accept variable. This is related to Zendesk Guide customization.

For this line:

https://XYZ.zendesk.com/api/v2/help_center/articles/search.json?label_names=LLC',

I would like to replace LLC with a variable value that is passed from HTML.

See code below:

<div>
    {{#if article.labels}}
    {{#each article.labels}} 

    <p>Articles related to <b> {{identifier}} :</b></p>
        <ul class="related">
        <p id="Project"></p>
    </ul>

    {{/is}} 
    {{/each}}
    {{/if}}

    <script type="text/javascript">
        <!-- create elements for LLC articles -->

        function createNode(element) {
          return document.createElement(element);
        }

        function append(parent, el) {
         return parent.appendChild(el);
        }

        <!-- list LLC articles-->

        const ul = document.getElementById('Project');
        const url = 'https://XYZ.zendesk.com/api/v2/help_center/articles/search.json?label_names=LLC';

        fetch(url)
            .then((resp) => resp.json())
            .then(function(data) {

        let family = data.results;

        return family.map(function(article) {
            let li = createNode('li'),
            span = createNode('span');
            span.innerHTML = "<a href ="+`${article.html_url}`+">"+`-    ${article.title}`+"</a>";
            append(li, span);
            append(ul, li);
            })
        })

            .catch(function(error) {   
                console.log(error);
            });
        }
    </script>

From the above HTML, the value of LLC is retrieved from {{identifier}}. I need to pass the value of {{identifier}} to the JavaScript code to replace LLC. How could I achieve this?

Upvotes: 2

Views: 150

Answers (1)

Sushanth --
Sushanth --

Reputation: 55740

You you have the LLC variable available, then it is just a matter of simple string concatenation.

const LLC = "something";
const url = 'https://XYZ.zendesk.com/api/v2/help_center/articles/search.json?label_names=' + LLC;

You can also use template string literals if there is support for ES6.

const LLC = "something";
    const url = `https://XYZ.zendesk.com/api/v2/help_center/articles/search.json?label_names=${LLC}`;

Upvotes: 1

Related Questions