Onclick: change form values and submit

I’m trying to change the value of two form variables and submit the form when a link is clicked. The following changes the values:

<a href=“#” onclick=“document.getElementById(‘name’).value = ‘The Name’; document.getElementById(‘category’).value = ‘The Category’;”>Anchor Text</a>

and the following submits the form, but it doesn’t change the values:

<a href=“#” onclick=“document.getElementById(‘name’).value = ‘The Name’; document.getElementById(‘category’).value = ‘The Category’; document.getElementById(‘form’).submit();”>Anchor Text</a>

Can I do both inline like this?

Yes, you can. But why do you say that this does not change the values:

<a href=“#” onclick=“document.getElementById(‘name’).value = ‘The Name’; document.getElementById(‘category’).value = ‘The Category’; document.getElementById(‘form’).submit();”>Anchor Text</a>
?

What I would do is use an event handler to call a function before the form is submitted.
Within this function you can then do whatever you like.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Validate phne number</title>
  </head>
  <body>
    <form id="myForm">
      <p>
        <label for="firstName">Please enter your first name:</label>
        <input type="text" id="firstName" />
      </p>

      <input type="submit" value="Submit">
    </form>

  <script>
    var f = document.getElementById('myForm');
    f.onsubmit = function(){
      alert("Hi, " + f.firstName.value + "!");
      // Do other stuff here ...
    }
  </script>
  </body>
</html>

Yes, you can. But why do you say that this does not change the values

Now that I look again, I think you’re right. I think the problem is that some server-side Perl which executes when the actual Submit button is clicked, doesn’t execute when the Javascript onclick is clicked. Can I cause a click on the Anchor Text to submit the form via the Submit button so that the behavior is the same as when the Submit button is clicked?

I would like to do this inline instead of with a separate Javascript event handler. This is a back-end page so I feel OK about it.

Hi,

I’m not so up on my Perl, but I would have thought that a Perl script has no concept of how it receives a set of form values, so I would be surprised if this was the problem.

One thing that did cross my mind, however: that browsers do not fire a submit event when a form is submitted via the submit() method.
Could this be the case? Do you have an onsubmit event listener in your code?