Home > Net >  Hyperlink (<a>) not working on Button (<button>)
Hyperlink (<a>) not working on Button (<button>)

Time:09-22

So I have a list of files that is generated as buttons, which allows a user to highlight them onClick. I also have the file name generated as a hyperlink, so users can download the files directly.

The button seems to be overwriting the hyperlink, and I'm wondering what I can do to get it to recognize my hyperlink click. The hyperlink still underlines when hovered on, so it seems to be registering my cursor, just not the click.

<button name="error_php_troubleshooting.txt" value="error_php_troubleshooting.txt" id="error_php_troubleshooting.txt"  onclick="DevTracker.fileList('error_php_troubleshooting.txt'); return false;" style="background-color: rgba(255, 229, 143, 0.51);">
<a  href="#" title="Delete File" onclick="DevTracker.deleteFile('error_php_troubleshooting.txt');return false;">X</a>
<a  href="files/TEST02/error_php_troubleshooting.txt">error_php_troubleshooting.txt</a>
</button>

I'm assuming the onClick event is overriding the hyperlink, but oddly enough, the X delete onClick registers. I tried playing with the z-transform to bring it up to the top layer, but it doesn't seem to be working.

I'm sure this is something really silly, but I can't seem to Googl;e the right combo to yield me the results I want.

CodePudding user response:

HTML does not allow buttons to contains links or vice versa.

Use the appropriate, semantic element (a link to link to a URL, a button to submit a form or hang JavaScript from, a checkbox to make a selection) and then apply CSS as desired.

If you need multiple controls next to each other that do different things when clicked: Put them next to each other, not inside each other.

CodePudding user response:

There are a few options you can pursue:

  1. Attach onclick functionality to the button, to follow the desirable link/URL, like so:

<button onclick="location.href='http://www.example.com'" type="button"> www.example.com</button>

  1. Style a tag for it to look like button

CodePudding user response:

Parent Element OnClick will always get precedence. As you mentioned your deleteLink gets registered but its OnClick wont function as there exists a Parent button OnClick.

Similar case for your Hyperlink.

Please check below I have tried an example to make your case work, even this DOES NOT WORKS

    <button name="b1" value="b1" id="b1"  onclick="window.location.href='https://w3docs.com';" style="background-color: rgba(255, 229, 143, 0.51);">
<a  href="#" title="X" onclick="window.location.href='https://www.youtube.com/';return false;">X</a>
<a  onclick='abc(event);' href="https://stackoverflow.com/">Y</a>
    </button>
<script>
function abc(event) { 
event.preventDefault();
      var href = event.currentTarget.getAttribute('href')
      window.location=href;
    }
    </script>

What you can do is separate button and anchor tag functionalities.

  • Related