Question

I have a couple of images that I use as buttons to trigger a javascript function.

Previously, I've always done this with e.g.

<a href='javascript:myFunction();'><img src="images/myButton.gif" alt="Click Here"/></a>

However, I recently saw examples of using a form input instead, which has the advantage of not producing link artefacts around the button image. This is what I started with.

<form><input type="image" src='images/myButton.png' id="startButton" onClick="myFunction()"></form>

For some reason, this cause the button to trigger a different function as well as the one designated with onlick.

I was about to go back to my tried and true href method, when I thought of removing the form tags, leaving only the input. All worked perfectly!

So my questions are:

  1. Is this safe? I've never seen examples of input tags used outside of forms.
  2. Why would a blank form tag trigger a javascript function? I realise it is intended to send data off to a server, but I thought if I left it blank, it would just sit there.
Était-ce utile?

La solution

It's not commonly used I think but it's valid as far as I know.

You can also use <button onClick="myfunction">name</button> .

Autres conseils

This is safe, and the reason that click on the button triggers another function could be that startButton ID has a selector that executes some stuff in your JS code.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top