skip to Main Content

I have a modal with a form.

<form id="timesheetform" action="code.php" method="POST"> 

The form has the button of type=submit and name="inserttimesheetrecord".

<button type="submit" style="float: left;" name="inserttimesheetrecord"  id="inserttimesheetrecord" class="btn btn-success btn-sm" >Submit</button>

The code to insert the record into a database table is stored in separate php file called code.php.

This was working fine.

Then I added a script to check the validity of the data. As a result the submit button’s id "inserttimesheetrecord" no longer passes to code.php

The code for this is:

document.getElementById("timesheetform").addEventListener("submit", function(event) {
// Prevent the form from submitting by default
event.preventDefault();

// Check if all required fields are filled
const date = document.getElementById('date').value;
const hours = document.getElementById('hours').value;
const ordernumber = document.getElementById('myInput').value;
const ordertype = document.getElementById('orderType').value;
const steptask = document.getElementById('StepTaskInput').value;
const notes = document.getElementById('notes').value;
    
const validationMessage = document.getElementById('validationMessage');

console.log(hours);

let missingFields = [];

if (!date) {
    // Need to change this to check the date is within 14 days.
    missingFields.push('date');
}
if (!hours || hours<=0) {
    missingFields.push('hours');
}
if (!ordernumber) {
    missingFields.push('ordernumber');
}
if (ordertype=='Non-Charge' && !notes) {
    missingFields.push('notes');
}
if (ordertype!='Non-Charge' && !steptask) {
    missingFields.push('StepTaskInput');
}
if (missingFields.length > 0) {
    validationMessage.innerHTML = `Please fill in the following fields: ${missingFields.join(', ')}.`;
} else {
    validationMessage.innerHTML = ''; // Clear any previous validation message
    // If all fields are filled, submit the form
    this.submit();
    //document.getElementById("timesheetform").submit();
}

}); 

In addition to this.submit(); I also tried document.getElementById("timesheetform").submit(); but neither passed the id which means if(isset($_POST['inserttimesheetrecord'])) does return tree and process the record.

How do I ‘pass’ the submit button name to code.php when using a script?

2

Answers


  1. You will need to allow the default processing to occur if things are valid. Like:

    document.getElementById("timesheetform").addEventListener("submit", function(event) {
    
        // Check if all required fields are filled
        const date = document.getElementById('date').value;
        const hours = document.getElementById('hours').value;
        const ordernumber = document.getElementById('myInput').value;
        const ordertype = document.getElementById('orderType').value;
        const steptask = document.getElementById('StepTaskInput').value;
        const notes = document.getElementById('notes').value;
        
        const validationMessage = document.getElementById('validationMessage');
    
        console.log(hours);
    
        let missingFields = [];
    
        if (!date) {
            // Need to change this to check the date is within 14 days.
            missingFields.push('date');
        }
        if (!hours || hours<=0) {
            missingFields.push('hours');
        }
        if (!ordernumber) {
            missingFields.push('ordernumber');
        }
        if (ordertype=='Non-Charge' && !notes) {
            missingFields.push('notes');
        }
        if (ordertype!='Non-Charge' && !steptask) {
            missingFields.push('StepTaskInput');
        }
        if (missingFields.length > 0) {
            // Prevent the form from submitting by default
            event.preventDefault();
            validationMessage.innerHTML = `Please fill in the following fields: ${missingFields.join(', ')}.`;
        }
    
    });
    
    Login or Signup to reply.
  2. Instead of using the submit event for validating the form you can let the build in validation do it for you. Here I have added attributes to the different form field to validate against. And a title attribute for displaying help to the user when the mouse hover the input.

    Use the invalid event for reporting back to the user. If everything is ok the form will submit. I changed the name of the button to "record" and added a value attribute to the button — not important, but could make more sense on the backend.

    BTW: When you submit a form using JavaScript use requestSubmit() and parse the button as parameter insted of using submit(). Something like: document.forms.timesheetform.requestSubmit(document.forms.timesheetform.record) in the case of the following example.

    const validationMessage = document.getElementById('validationMessage');
    
    document.forms.timesheetform.addEventListener('invalid', e => {
      e.target.classList.add('invalid');
    }, true);
    
    document.forms.timesheetform.addEventListener('invalid', e => {
      let form = e.target.form;
      let invalid = [...form.elements].filter(elm => !elm.validity.valid);
      if(invalid.length > 0){
        validationMessage.textContent = 'Please fill in the following fields: ' + invalid.map(elm => elm.name).join(', ');
      }
    }, true);
    
    // this third event listener is just for preventing the default
    // error message from showing up.
    document.forms.timesheetform.addEventListener('invalid', e => {
      e.preventDefault();
    }, true);
    
    document.forms.timesheetform.addEventListener('input', e => {
      let form = e.target.form;
      if(e.target.validity.valid){
        e.target.classList.remove('invalid');
      }
      if(form.reportValidity()){
        validationMessage.textContent = '';
      }
    });
    form {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      gap: .3em;
    }
    
    .invalid {
      border: solid red 2px;
    }
    <form name="timesheetform" action="code.php" method="POST">
      <label>Date<input type="date" name="date" required></label>
      <label>Hours<input type="number" min="1" max="12" name="hours" required title="Number between 1 and 12"></label>
      <label>Order number<input type="number" pattern="[0-9]{5}" name="ordernumber" required title="5 digit number"></label>
      <label>Order type<select name="ordertype" required>
      <option value="1">Type 1</option>
      <option value="2">Type 2</option></select></label>
      <label>Step task<input type="text" minlength="1" name="steptask" required title="Minimum 12 characters"></label>
      <label>Notes<textarea name="notes" minlength="1" required title="Minimum 12 characters"></textarea></label>
      <button type="submit" name="record" value="inserttimesheet" class="btn btn-success btn-sm">Submit</button>
    </form>
    <p id="validationMessage"></p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search