Question

I'm struggling a bit with joining jstl and jquery. I have a Spring aplication which provides me with a list, for example cars: [Kia, Audi, Fiat, Mazda, Opel]

I have an input field that if the user presses the button next to it, it adds this text in form of fancy tag, or whatever. Furthermore I want to add all list elements in same form of this tag while the page loads. But if I try I receive :

Uncaught ReferenceError: add_tag is not defined (anonymous function)

So I have code as follows (of course strip down to very problem)

<script>
    $(document).ready(function() {
        function add_tag(value) {
            console.log("adding tag:" + value);
            //some styling
            $("#add_here").append(value);
        };

        $("#add_tag").click(function() {
            add_tag($("#choosen_tag").val());
        });
    });
</script>

<div>
    <c:forEach items="${cars}" var="c">
        <script>
            add_tag("${c}");
        </script>
    </c:forEach>
</div>

<input id="choosen_tag"></input>
<button type="button" class="btn btn-default" id="add_tag">+</button>
<div id="add_here"></div>

All jquery, jstl tags etc, are of course included. The sole issue here is calling this function. Tried something with named functions, or declaring it within some other var, still no success :/

Was it helpful?

Solution

Minutes after posting, I found a solution. Script should use jstl instead of the other way around. Adding

<script> $(document).ready(function() { 
<c:forEach items="${cars}" var="c"> 
    add_tag("${c}"); 
</c:forEach> 
// rest of script adding functions
...

solves my issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top