Merging onsubmit scripts

I have a form which has two scripts that run on submit; one to disable the submit button after being clicked once, the other to add the uk country code to the phoneNumber field. I can only get one of them to run at a time, how can i get them to both run?

  <form action="https://123.com" method="post" onsubmit="return checkForm(this);"> 
   <input name="PhoneNumber" type="tel" required="">
   <input name="myButton" type="submit" value="Submit">
   </form>
 <script type="text/javascript">
  function checkForm(form)
  {
    //
    // validate form fields
    //

    form.myButton.disabled = true;
    return true;
  }
</script> 
  <script>
function checkForm(f) {
  const phoneNumberField = f.querySelector("[name='PhoneNumber']");
  if(phoneNumberField.value.startsWith("0")){
    phoneNumberField.value = "44" + phoneNumberField.value.substring(1);
  }
   return true; // Just for demo to stop the form submitting
}
  </script> 
 

1 thought on “Merging onsubmit scripts”

  1. Don’t use onclick attribute. Use Element.addEventListener() instead

    document.getElementById('my-form').addEventListener('submit', checkForm)
    
    function checkForm1(form) {
      form.myButton.disabled = true;
    }
    function checkForm2(f) {
      const phoneNumberField = f.querySelector("[name='PhoneNumber']");
      if (phoneNumberField.value.startsWith("0")) {
        phoneNumberField.value = "44" + phoneNumberField.value.substring(1);
      }
    }
    function checkForm(e) {
      checkForm1(e.target)
      checkForm2(e.target)
      e.preventDefault()
      e.stopPropagation()
      return false;
    }
    <form id="my-form" action="https://123.com" method="post">
      <input name="PhoneNumber" type="tel" required="">
      <input name="myButton" type="submit" value="Submit">
    </form>

    OR

    document.getElementById('my-form').addEventListener('submit', checkForm1)
    document.getElementById('my-form').addEventListener('submit', checkForm2)
    document.getElementById('my-form').addEventListener('submit', cancel)
    
    function checkForm1(e) {
      e.target.myButton.disabled = true;
    }
    
    function checkForm2(e) {
      const phoneNumberField = e.target.querySelector("[name='PhoneNumber']");
      if (phoneNumberField.value.startsWith("0")) {
        phoneNumberField.value = "44" + phoneNumberField.value.substring(1);
      }
    }
    
    function cancel(e) {
      e.preventDefault();
      e.stopPropagation();
      return false;
    }
    <form id="my-form" action="https://123.com" method="post">
      <input name="PhoneNumber" type="tel" required="">
      <input name="myButton" type="submit" value="Submit">
    </form>
    Reply

Leave a Comment