0

In my javascript I have an array of 3 elements:

var array = ["one", "two", "three"]; 

How do I create 3 html buttons such that each button's onclick calls a function with parameter array[i].

for result i want to have:

<button onclick='function("one")'></button>
<button onclick='function("two")'></button>
<button onclick='function("three")'></button>
Nemanja Zunic
  • 51
  • 1
  • 10

3 Answers3

0

To get you running quick here is a quick fix to your existing code.

If you say the buttons will be in order then you can make use of the indexes of the button.

var array = ["one", "two", "three"]; 

function Myfunction(e){
  var index = $('.container button').index(e.target)
  alert(array[index]);  // now you have the value here, use it for your further stuff
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button onclick='Myfunction(event)'></button>
<button onclick='Myfunction(event)'></button>
<button onclick='Myfunction(event)'></button>
  </div>

If you are looking for a cleaner way then I would recommend not to use the onclick attribute to bind event and directly bind events using Jquery. Like below..

var array = ["one", "two", "three"];

$('.container button').on('click', function() {
  var index = $('.container button').index($(this));
  alert(array[index]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <button ></button>
  <button ></button>
  <button ></button>
</div>
Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
0

Using inline handler will give us troubles at times. For example by accessing current element using this inside the event handler. So here in this case, You can do it with dataset and addEventListener.

var array = ["one", "two", "three"];
array.forEach(function(itm){
  var elem = document.createElement("button");
  elem.textContent = itm;
  elem.dataset.data = itm;
  elem.addEventListener("click", clickHandle, false);
  document.body.appendChild(elem);
});

function clickHandle(){
  alert(this.dataset.data); //will display "one"/"two"/"three" based on the element clicked.
}

DEMO

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
-1
var btn_list;   //The buttons parent element
var your_func;  //callback function
for (var i = 0; i < array.length; i++)
{
    btn = document.createElement('BUTTON'); //create element
    btn.onclick = function() //assign callback, with item
    {
        your_func(array[i]);
    };
    btn_list.appendChild(btn); //and add it to parent element
}

where of course, your callback function and your buttons parent element were defined before....

Vincent
  • 1,016
  • 6
  • 11
  • This won't work because of the [infamous loop issue](http://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue) – Barmar Apr 18 '16 at 15:46