I am drawing the svg which has four rectangles, and each rectangle has specific text(label). I have a requirement to be able to edit the text and it should take the label defined by user. I tried few things like using input box and also contenteditable true attribute for the text, but nothing seems to be working for me. I have shared the part of my code and also jsfiddle link.
const drawSvg= svg.append("g")
. append("rect")
.attr("id", "myRect")
. style("fill", function (d) {color});
g.selectAll("g"). append("text").attr("id", "myText")
.text (function (d) {return label;});
https://jsfiddle.net/ypvoxf6h/4/
CodePudding user response:
if the problem is to change the inner text, you can put a class in each text, select it by class, change the inner text.
const svg = document.querySelector('#mySVG').querySelector('.text1').innerHTML = 'A';
<svg id="mySVG" viewBox="0 0 4 2" width="400px">
<g dominant-baseline="middle" text-anchor="middle" font-size=".73">
<rect x="0" y="0" height="1" width="1.2" style="fill: rgb(255, 46, 0);"/>
<text x="0.2" y="1.5" style="fill: black;">0</text>
<rect x="1" y="0" height="1" width="1" style="fill: rgb(0, 184, 0);"/>
<text x="1.5" y="1.5" style="fill: black;">1</text>
<rect x="2" y="0" height="1" width="1" style="fill: rgb(0, 25, 255);"/>
<text x="2.5" y="1.5" style="fill: black;">2</text>
<rect x="3" y="0" height="1" width="1" style="fill: rgb(179, 179, 179);"/>
<text x="3.5" y="1.5" style="fill: black;">3</text>
</g>
</svg>
CodePudding user response:
yes you had everything to do that, just to add the input change...
document.querySelector('#text1').addEventListener('change', function(evt) {
document.querySelector('#mySVG').querySelector('.' evt.target.id).innerHTML = evt.target.value;
})
<svg id="mySVG" viewBox="0 0 4 2" width="400px">
<g dominant-baseline="middle" text-anchor="middle" font-size=".73">
<rect x="0" y="0" height="1" width="1.2" style="fill: rgb(255, 46, 0);"/>
<text x="0.2" y="1.5" style="fill: black;">0</text>
<rect x="1" y="0" height="1" width="1" style="fill: rgb(0, 184, 0);"/>
<text x="1.5" y="1.5" style="fill: black;">1</text>
<rect x="2" y="0" height="1" width="1" style="fill: rgb(0, 25, 255);"/>
<text x="2.5" y="1.5" style="fill: black;">2</text>
<rect x="3" y="0" height="1" width="1" style="fill: rgb(179, 179, 179);"/>
<text x="3.5" y="1.5" style="fill: black;">3</text>
</g>
</svg>
<label for="text1">text 1
<input id="text1" value="0"></label>
Done for text1... you can copy & paste for the others