1

I am trying to create a graph using svg element and then appending a rect element for each bar of the graph in a loop.

How do I pass the "moveBar" variable into the .append statement to adjust the width attribute of the rect element?

        $(document).ready(function () {
            var ulEmployees = $('#ulEmployees');
            var moveBar = 0;

            $('#btn').click(function () {
                $.ajax('api/AnnualPowerInterruptions', {
                    dataType: 'json',
                    success: function (data) {
                        ulEmployees.empty();
                        $('#graphData2').append("<svg id=mySVG class='chart' width='500' height='500'></div>");
                        $.each(data, function (index, val) {
                            var name = val.year;
                            ulEmployees.append('<li>' + name + '</li>');
                            $('#mySVG').append("<g transform='translate (100, 0)'><rect width=moveBar 'height='40' style='fill:red'> </rect> <text x='-50' y='30' fill='red'> blue </text></g>");
                            window.alert(moveBar);
                            moveBar = moveBar + 50;
                        });
                        $("#graphData2").html($("#graphData2").html())
                    }

                });

            });
            <div id="graphData2">
            </div>

1 Answer 1

1

You can use Template literals to assign variable value to your rect tag like this:

$(document).ready(function() {
  var ulEmployees = $("#ulEmployees");
  var moveBar = 0;

  $("#btn").click(function() {
    $.ajax("api/AnnualPowerInterruptions", {
      dataType: "json",
      success: function(data) {
        ulEmployees.empty();
        $("#graphData2").append(
          "<svg id=mySVG class='chart' width='500' height='500'></div>"
        );
        $.each(data, function(index, val) {
          var name = val.year;
          ulEmployees.append("<li>" + name + "</li>");
          $("#mySVG").append(
            `<g transform='translate (100, 0)'><rect width=${moveBar} 'height='40' style='fill:red'> </rect> <text x='-50' y='30' fill='red'> blue </text></g>`
          );
          window.alert(moveBar);
          moveBar = moveBar + 50;
        });
        $("#graphData2").html($("#graphData2").html());
      }
    });
  });
});
<div id="graphData2">
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.