shlagwuk
shlagwuk

Reputation: 93

Css style to dynamic content with jquery/ajax

Here is my jquery (3.1.1)/ajax request:

$.ajax({
      type: "POST",
      url: "pref.php",
            dataType: "text",
      data: { groupe_id: groupe_id, action: "getProducts" },
      cache: false,
            error: function(html){
                console.log(html);
            },
      success: function(html) {
                    $("#listProducts").html(html);
      }
    });

The html response for #listProducts is as follow (with bootstrap css loaded before):

<div class="row">  
  <div class="form-group row col-xs-4">
    <label class="col-xs-3 text-right" for="productName-72"><b>Name:</b></label>
    <div class="col-xs-9">
      <input type="text" class="form-control form-control-sm product-name" id="productName-72" aria-describedby="productName">
    </div>
  </div>
...
</div>

But there is no style applied to this part of code.

What can I do to make it load the bootstrap.css style?

Upvotes: 1

Views: 1689

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Make sure that you're including the bootstrap css file, e.g :

<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

The dynamically added elements to the DOM should work just fine with bootstrap check the example below.

NOTE : No need for the extra row class in form-group row col-xs-4.

Hope this helps.

$('#listProducts').append('<div class="row"><div class="form-group col-xs-4"><label class="col-xs-3 text-right" for="productName-72"><b>Name:</b></label><div class="col-xs-9"><input type="text" class="form-control form-control-sm product-name" id="productName-72" aria-describedby="productName"></div></div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>

<div id="listProducts"></div>

Upvotes: 2

user4754887
user4754887

Reputation:

Make sure your bootstrap css file is loaded on the page before the ajax request and the styles will automatically apply on the newly added content.

So, you dont need to "load" bootstrap(css files) for each consecutive request, just keep the css file loaded on the page

Upvotes: 0

Related Questions