onur sayın onur sayın -4 years ago 101
Javascript Question

dynamic button with jquery

I created a dynamic button. But the value of all buttons is the same. what should I do for this? I want every one to have different values.

Example image



for (var i = 0; i <= 11; i++) {
var r = $('<input type="button" value="new button" style="margin-left:10px; margin-top:5px;"/>');
$("#sth").append(r);

$("#sth").css({
width: '300px',
'padding-top': '10px',
'padding-bottom': '10px',
'padding-left': '10px'
});
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="sth"></div>




Answer Source

You can use index to change the value of each button. See if this helps.

for (var i = 0; i <= 11; i++) {
        var r = $('<input type="button" value="new button ' + i + '" style="margin-left:10px; margin-top:5px;"/>');
        $("#sth").append(r);

        $("#sth").css({ width: '300px', 'padding-top': '10px', 'padding-bottom': '10px', 'padding-left':'10px' });}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id='sth'></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download