Venkat Cpr
Venkat Cpr

Reputation: 163

How to pass varaiable in HTML functions through jquery

this is my html code. group.participants is an array.

result +=`<button class="gsb-${group.id}" onclick="demo(${group.participants})">`+"DEMO"+`</button><br/>`;

this is my simple javascript code to display the array from the parameter

 function demo(participants){
            alert(participants);
        }

this shows me the error

Uncaught SyntaxError: Unexpected end of input

may I know what is the problem

Upvotes: 0

Views: 40

Answers (1)

jeremy-denis
jeremy-denis

Reputation: 6878

With Jquery you can use the following to pass data to a selector

$(`.gsb-${group.id}`).data(group.participants); 

to recover it you just have to call data() method

$(`.gsb-${group.id}`).data(); 

Finally like each group have different participants, you will have to append first the group button before add the data to it

result.append(`<button class="gsb-${group.id}" onclick="demo(${group.id})">`+"DEMO"+`</button><br/>`);
$(`.gsb-${group.id}`).data(group.participants);

    function demo(groupId) {
       var participants = $(`.gsb-${groupId}`).data();
       console.log(participants);
    }


    var result = $('#result');
    var group = {
      id:1,
      participants:[
        {name:'test1'},
        {name:'test2'}
     ]
    }
    result.append(`<button class="gsb-${group.id}" onclick="demo(${group.id})">`+"DEMO"+`</button><br/>`);
    $(`.gsb-${group.id}`).data(group.participants);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>

Upvotes: 1

Related Questions