MR Grow A Lot MR Grow A Lot - 3 months ago 14
Javascript Question

jQuery putting a variable in a variable containing a html string

I'm trying to get this variable:

var company;
to work in the next line.

var newcomp ='<button type="button" class="list-group-item" data-database=""><script>var company;</script></button>';


var newcomp ='<button type="button" class="list-group-item" data-database="">'+ company + '</button>';


the script tags where the problem.

In the future i will try to improve my questions. Thx for the help guys.

Answer

Remove the <script> tag inside your button and escape company:

var company = $("#newCompAdd").val();
var newcomp = '<button type="button" class="list-group-item" data-database="">' + company + '</button>';

Your full example code:

$(document).ready(function() {
  $(document.body).on("click", "#formAddNewCompanySave", function() {
    var company = $("#newCompAdd").val();
    alert(company);
    var newcomp = '<button type="button" class="list-group-item" data-database="">' + company + '</button>';
    $('#companylist').append(newcomp);

    $.ajax({
      method: "POST",
      url: "addCompany.php",
      data: {}
    });
  });
});