-1

I need to get access to a different server if input field "account" is longer than 10 characters, how can I change the form action target to server2 with JavaScript dynamically?

<form method="get" action="server1/login.php"
    class="get-started-form flex items-center flex-wrap">
  <input name="account" type="text"
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Tom
  • 6,725
  • 24
  • 95
  • 159

1 Answers1

1

You can listen to the keyup event on the input box to detect whenever the text value changed, then read the value using the value property. After that, compare the length and dynamically modify the action property of the form element based on your needs.

const getStartedForm = document.querySelector('.get-started-form');
const accountInput = document.querySelector('input[name="account"]');
accountInput.addEventListener('keyup', () => {
  if (accountInput.value.length > 10) {
    getStartedForm.action = 'server2/login.php';
  } else {
    getStartedForm.action = 'server1/login.php';
  }
});
<form
  method="get"
  action="server1/login.php"
  class="get-started-form flex items-center flex-wrap"
>
  <input name="account" type="text" />
</form>
AngYC
  • 3,051
  • 6
  • 20