Oscar Ordoñez
Oscar Ordoñez

Reputation: 23

Send a array in a onclick function

function show(array){
  console.log(array);
}

function main() {
  var send = ["HOLA", "ADIOS"];
  $('#table').append('<tr>'+
                    '<td style="width: 35%">Oscar</td>'+
                    '<td style="width: 6%">'+
                        '<button type="button" class="btn btn-success" data-dismiss="modal" onclick=show('+send+')>+</button>'+
                    '</td>'+
                '</tr>'
   );
}
main();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table" class="table table-bordered">
	<thead>
		<tr>
		  <th style="width: 35%" id="wallet-modal-table-name-header"></th>
			<th style="width: 6%"  id="wallet-modal-table-options-header"></th>
		</tr>
	</thead>
</table>

I have this code and I want to send the array "send" but when I send it as a parameter in the functions it shows me an error. What could I do?

Upvotes: 0

Views: 1198

Answers (2)

Ele
Ele

Reputation: 33736

For dynamically created elements, use the Event delegation approach:

$(selector4parent).on(event, selector4children, handler);

function show(array) {
  console.log(array);
}

function main() {
  $('#table').on('click', '[type="button"]', function(e) {
    var send = ["HOLA", "ADIOS"];
    show(send);
  });


  $('#table').append('<tr>' +
    '<td style="width: 35%">Oscar</td>' +
    '<td style="width: 6%">' +
    '<button type="button" class="btn btn-success" data-dismiss="modal">+</button>' +
    '</td>' +
    '</tr>'
  );
}
main();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table" class="table table-bordered">
  <thead>
    <tr>
      <th style="width: 35%" id="wallet-modal-table-name-header"></th>
      <th style="width: 6%" id="wallet-modal-table-options-header"></th>
    </tr>
  </thead>
</table>

Upvotes: 1

Thomas
Thomas

Reputation: 442

You can create your button outside of the string then append it to the TD you would like it in.

var $btn = $(document.createElement("BUTTON"));
$btn.attr({ 'type': 'button', 'data-dismiss': 'modal'}).addClass('btn btn-success');

$btn.click(function()
{
    show(send);
});

$('td-selector').append($btn);

Upvotes: 0

Related Questions