0

I have an input box with an SVG circle inside of it:

input{
background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='30' height='30'><circle cx='15' cy='15' r='10' /></svg>")  no-repeat;
}

Using Javascript how can I change the color of the circle to red (say when a user enters something illegal)?

Luves2spooge
  • 78
  • 1
  • 8

2 Answers2

1

As i read your description, 1) You need to add style in javascript event base on your functionality [like on change or on form submit where ever you want to validate]

2) Please fix minor change "fill='#f00'" in below css:

background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='30' height='30' fill='#f00'><circle cx='15' cy='15' r='10' /></svg>")  no-repeat;
Sunil Boricha
  • 446
  • 3
  • 9
  • Correct. So how do I change `fill` from within Javascript? Alternatively, how do I change the circle from hidden to shown (since the circle doesn't always need to be visible)? – Luves2spooge Aug 24 '17 at 07:31
  • Just put 1 extra class in css apply style already given in Answer then append this class in input using JavaScript. – Sunil Boricha Aug 24 '17 at 07:39
1

If you want to use the svg as a css background as mentioned you will have to have a separate class with a red background svg that you can swap out

<input class="a" onchange="checkValue(event)" type="text" name="a">

function checkValue(event){
  var input = event.target; 
  if(input.value.length<2){
    input.className = "error";
  }else{
    input.className = "";
  }
}

input{
  background:background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='30' height='30'><circle cx='15' cy='15' r='10' fill="black" /></svg>")  no-repeat;
}

.error{
  background:background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='30' height='30'><circle cx='15' cy='15' r='10' fill="red" /></svg>")  no-repeat;
}
iSZ
  • 682
  • 5
  • 10