Jacob Davis
Jacob Davis

Reputation: 21

How do I make html run a javascript function when a user clicks a button?

I have a web form where users will type in a name of a person then click a button to open a page about that person. e.g. They type Player One and it runs a function which opens the file C:\PlayerOne.

I've tried using the <button> tag and adding the onclick element to run the function, but I was unable to diagnose the problem there either. The Event Listener stuff I am not too familiar with, but I saw it [here] (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/button) so I thought I'd try it that way instead.

<form>
  <fieldset>
    <legend>Enter player name: </legend>
    First name:<br>
    <input type="text" name="firstname"><br>
    Last name:<br>
    <input type="text" name="lastname"><br><br>
    <input type="button" value="Submit">
  </fieldset>

  <script>
    const input = document.querySelector('button');
    input.addEventListener('click', UseData);
    function UseData()
        {
        var Fname=document.GetElementById('firstname');
        var Lname=document.GetElementById('lastname');
        window.location = "C:\" + Fname + Lname;
        }
  </script>
</form>  

I want the user to be able to type the name and open the appropriate file, as explained above. However, the button at this point simply does nothing. I do have a test file for it to reference, which I have been typing the name of in the fields of the form.

Upvotes: 1

Views: 70

Answers (2)

Jerry D
Jerry D

Reputation: 391

Here is an example of similar code by me involving a button triggering a function

The button:

 <button onclick="theFunction()">sampletext</button>

The script:

    var x = document.getElementById("sampleElement");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

In my example, the button is used to show/hide a div. Clicking my button triggers the function which changes the div visibility.

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44145

It's because there's no button tags in your form. Use the attribute selector like so instead:

const input = document.querySelector('input[type="button"]');

Upvotes: 3

Related Questions