U.f.O
U.f.O

Reputation: 299

Creating bootstrap buttons dynamically

Is it possible to create bootstrap button dynamically? I have a textfile that have a list of items where I will make use of javascript to create an array with. That is where I would like to create bootstrap buttons dynamically with those items being the text within each button. If there is 10 items in the textfile, there would be 10 buttons created. Can someone tell me how can it be done or point me to some tutorial about it.

EDIT(Creation is possible now but not code for checking if buttons is created):

createButtons():

$(function() {
  $.ajax({
    url : 'http://localhost:8080/SSAD/type.txt',
    dataType : "text",
    success : function (filecontent) {
      var lines=filecontent.split('\n');
      $.each(lines, function() {
        if (this!='') {
            var word = this;
            word = word.toLowerCase().replace(/(?:_| |\b)(\w)/g, function(str, p1) { return p1.toUpperCase();});
            if ($('button:contains("'+word+'")').length==0) {
                var button='<button type="button" class="btn btn-block btn-inverse active" data-toggle="button tooltip" title="Click this to enable/disable viewing of'+this+'" onclick="toggleVisibility('+"'"+this+"'"+')">'+word+'</button>';
                $(".crisisButtons").append(button);
            }
        }
      });
    }
  });
});

HTML:

<button type="button" class="btn btn-block btn-inverse" onclick="createButtons">Click me!</button>

<div class="crisisButtons"></div>

Upvotes: 3

Views: 11081

Answers (1)

davidkonrad
davidkonrad

Reputation: 85578

Yes. It is very easy.

textfile.txt

button1
button2
button3
button4
button5
button6
button7
button8
button9
button10

code

<div id="textfile-buttons"></div>

<script type="text/javascript">
$(document).ready(function() {
  $.ajax({
    url : 'textfile.txt',
    dataType : "text",
    success : function (filecontent) {
      var lines=filecontent.split('\n');
      $.each(lines, function() {
        if (this!='') {
          var button='<button class="btn btn-primary">'+this+'</button>&nbsp;';
          $("#textfile-buttons").append(button);
        }
      });
    }
  });
});
</script>

Result enter image description here

Of course you need to assign a click-handler to the buttons, or a link if you use <a> -tags instead of <button>.


Update

If you want to check if a button with a certain text already exists, modify the $.each loop

$.each(lines, function() {
  if (this!='') {
    //check if a button with "this" text not already exists
    if ($('button:contains("'+this+'")').length==0) {
      var button='<button class="btn btn-primary">'+this+'</button>&nbsp;';
      $("#textfile-buttons").append(button);
    }
  }
});

So, even if textfile.txt contains button1 button2 button3 button3 button3 button3 button7 button8 button9 button10

only one button3 will be created.

Upvotes: 7

Related Questions