Add options into select label (attempt to read options from js files)

A primary question,I defined a label in html file, and want to read options from a certain file (js), how can it be realized?
e.g.,in html,
< script type="text/x-red" data-template-name="">
<select> func</select>
</script>

<script type="text/javascript">
Object.keys(JSfileReturnArray).forEach(function(f) {
func.append($("").val(f).text(f));
})
</script>

Evening Qin,

Perhaps I understand this incorrectly, but do you want to show (in your node's config screen) a dropdown with options that you get from the server-side flow (js file)?

If so, in my type-converter node you can see in the html file how I fill a dropdown with options that I get (via an ajax call) from the server side Node-RED flow:

// Load the available categories from the server
$.getJSON('unit-converter/categories', function(data) {
        // Show all available categories in the dropdown
         for (i = 0; i < data.length; i++) {
                var category = data[i];
                $("<option value='" + category + "'> " + category.charAt(0).toUpperCase() + category.slice(1) + "</option>").appendTo("#node-input-category");
         }   
});

And in the js file you can find how the server-side will publish this data:

    // Make all the available types accessible for the node's config screen
    RED.httpAdmin.get('/unit-converter/:cmd', RED.auth.needsPermission('unitconverter.read'), function(req, res){
        var node = RED.nodes.getNode(req.params.id);
        
        if (req.params.cmd === "categories") {
            // Return a list of all available categories (mass, length, ...)
            res.json(your_list_of_categories);
        }
    });

Bart

2 Likes

Dear Bart,
Many thanks for your patience and solution.

Basically, your understanding is right. but the js file which will return the options is located on local, not on server-side.

Your solution is very helpful for me. I think I can solve my this issue by referring to your node.

1 Like

You cannot generally mix server and local files as that is a severe security issue. If you really need to do something like that, run Node-RED locally as well as on the server and then use the local version to combine data from the server.

For anyone who comes here looking for HTML-to-JS comm examples, note that this line in the JS code:

only returns the "node" if the node has been deployed. Otherwise it is "null".

( I don't think it actually is used for anything in the "unit-converter" code. )

That's correct. Though there are ways to also capture undeployed nodes via an event listener should you ever need to do that (I did :slight_smile: )