Cycling Paper Cycling Paper - 3 months ago 7
Javascript Question

JQuery dynamically added button, text not in button

When I attempt creating buttons from jQuery, the text appears outside of the button element I created. I've tried creating each button individually and as a group, and neither method seems to work. What am I doing wrong?

<div id = 'output_div'></div>

var main = function(){
var selections = ['derp', 'herp', 'merp', 'foo'];


//individually creating each button
for(var i = 0; i < selections.length; i++){
$('#output_div').append("<input type='button'>" + selections[i] +
"</input>");
};

$('#output_div').append('<br><br>');


//buttons all created at the same time
var group_buttons = '';

for(var i = 0; i < selections.length; i++){
group_buttons += ("<input type='button'>" + selections[i] + "</input>");
};

$('#output_div').append(group_buttons);
};

$(document).ready(main);


https://jsfiddle.net/fjr56Lsj/4/

Answer

Set the button text either as the value attribute of the <input>, or render the buttons as <button>:

$(function() {
  var selections = ['derp', 'herp', 'merp', 'foo'];

  for (var i = 0; i < selections.length; i++) {
    $('#output_div').append("<input type='button' value='" + selections[i] + "' />");
  };

  $('#output_div').append('<br><br>');

  for (var i = 0; i < selections.length; i++) {
    $('#output_div').append("<button>" + selections[i] + "</button>");
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output_div'></div>

Comments