user3577669
user3577669

Reputation: 13

Dynamically created button gets automatically fired

I am creating a dynamic unordered custom List view. In each element, there is one button. I am creating the list elements in the following way:

for (i = 0; i < arrayID.length; i++) {
    var listElement = '<li class="has-form">' +
        '<div class="row collapse">' +
        '<div class="small-1 columns" style="margin: 5px">' +
        '<img src="image/twitter.png">' +
        '</div>' +
        '<div class="small-6 columns small-only-text-center">' +
            '<p>' +
                '<i>' + arrayText[i] + '</i>' +
            '</p>' +
        '</div>' +
        '<div class="small-3 columns">' +
            '<button type="button" class="large-10" onclick="' + onClickViewButton() + '">view</button>' +
        '</div>' +
        '<div class="small-1 columns">' +
            '<input id="checkbox1" type="checkbox">' +
            '</div>' +
        '</div>' +
    '</li>';
    $("#myList").append(listElement);
}

The code for button click is:

function onClickViewButton() {
    alert('hello');
}

But unfortunately the when the page is loading, the button click is fired and not working on actual button click. Please help.

Upvotes: 0

Views: 47

Answers (2)

Rayon
Rayon

Reputation: 36599

Try with this snippet:

If you concat function name with parenthesis then it will be treated as function execution hence function will get called.

for (i = 0; i < arrayID.length; i++) {
  var listElement = '<li class="has-form">' +
    '<div class="row collapse">' +
    '<div class="small-1 columns" style="margin: 5px">' +
    '<img src="image/twitter.png">' +
    '</div>' +
    '<div class="small-6 columns small-only-text-center">' +
    '<p>' +
    '<i>' + arrayText[i] + '</i>' +
    '</p>' +
    '</div>' +
    '<div class="small-3 columns">' +
    '<button type="button" class="large-10" onclick="onClickViewButton()">view</button>' +
    '</div>' +
    '<div class="small-1 columns">' +
    '<input id="checkbox1" type="checkbox">' +
    '</div>' +
    '</div>' +
    '</li>';
  $("#myList").append(listElement);
}

Upvotes: 0

Maximillian Laumeister
Maximillian Laumeister

Reputation: 20359

Where you have:

onclick="'+onClickViewButton()+'"

you need to have:

onclick="onClickViewButton()"

instead.

Your current code calls the onClickViewButton function in your declaration, when what you really want to do is to just use it as a function reference so it gets called later on onclick.

Upvotes: 3

Related Questions