1

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/

2
  • input of type button has property called "value". You need to set it up. <input type="button" value="abc"/> Commented Aug 9, 2016 at 20:04
  • Sure. Fixed the issue here : jsfiddle.net/fjr56Lsj/5 Commented Aug 9, 2016 at 20:06

4 Answers 4

2

Another way to create a button using jquery would be as follows:

var dynamicButton = $('<button/>', {
    text: selections[i],
    id: 'dynamicButton_'+i
});
$('#output_div').append(dynamicButton);
Sign up to request clarification or add additional context in comments.

Comments

1

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

1

As input type button attribute , use value = selections[i] (keep Ur quotes careful)😉 else use button tag instead input element

Comments

1

The Button can be created in this fashion too:

$('<button/>', {
    text: selections[i]
 })

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


  //individually creating each button
  for (var i = 0; i < selections.length; i++) {

    $('#output_div').append($('<button/>', {
      text: selections[i]
    }));
  };

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

$(document).ready(main);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output_div'>

</div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.