John Lawrence Aspden John Lawrence Aspden - 4 months ago 62
HTML Question

Can I make an svg image button?

Is there any way of making a POST request when an svg image is clicked?

My best attempt so far looks like:

<form action="/test-button" method="POST">
<input name="Submit" type="submit" value="Submit" />
<svg >
<rect width="100" height="100" >
</svg>
</form>


Which is a black rectangle with a submit button next to it.

I want to allow people to choose between several images, so this may be an ok solution, but is there any way of making an image which, when clicked, will fire off a POST?

Extra points for not using javascript.

Answer

Warning: This is a little hacky, but as far as I know it's 100% legit, and doesn't need javascript.

Since the label element can also be used to control it's associated input, you could try something like this:

<form action="/test-button" method="POST">
  <label>
   <input type="submit" name="image" value="one">
   <svg><rect width="100" height="100"></rect></svg> 
  </label>
  <label>
   <input type="submit" name="image" value="two">
   <svg><rect width="100" height="100"></rect></svg> 
  </label>
</form>
 ‚Äč

Then hide the submit buttons with CSS. You can put anything in the label that you want.

When you click on whatever's in the label, it will trigger the submit button inside it and submit the form, with the button's value in the POST array.

There is also an <input type="image">, but that's for an entirely different purpose (tracking coordinates of where it was clicked).

Comments