Reputation: 85
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>
Upvotes: 1
Views: 1869
Reputation: 11622
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>
Upvotes: 1