skip to Main Content

I trying to make a simple form that getting the user input and display it on the browser, some function is working fine. When I put a letter inside the input box and a number on the second input box it display and add a new row that contain only the input which I put the number, also it continue adding if I continue clicking the submit. What I wanted to Implement is when user input letters and numbers on the form the form well not pursue until the user fix(replace the letter with number on the form) and not adding a new row on the table.

 let formSubmitted = false;

    function displayUserInput() {
        if (formSubmitted) {
            return; // Don't add more rows if the form has already been submitted
        }

        let total = 0;
        const table = document.querySelector("#outputTable tbody");
        const inputs = ["Input 1", "Input 2", "Input 3"];
        const errorDisplay = document.getElementById("errorDisplay");
        errorDisplay.textContent = ""; // Clear any previous error messages

        inputs.forEach((inputLabel, index) => {
            const inputField = document.querySelector(`#input${index + 1}`);
            const value = parseFloat(inputField.value);

            if (isNaN(value)) {
                errorDisplay.textContent = `Invalid input for ${inputLabel}. Please enter a number.`;

                // Automatically clear the error after 3 seconds (3000 milliseconds)
                setTimeout(() => {
                    errorDisplay.textContent = "";
                }, 3000);

                return; // Exit the loop if there's an error
            }

            total += value;

            const row = table.insertRow();
            row.insertCell(0).textContent = inputLabel;
            row.insertCell(1).textContent = value;
        });

        if (errorDisplay.textContent === "") {
            const average = total / inputs.length;
            document.getElementById("averageAmount").textContent = `Average Amount: ${average}`;
            formSubmitted = true; // Mark the form as submitted
        }
    }

    function clearInputs() {
        const inputFields = document.querySelectorAll("input[type='text']");
        inputFields.forEach((inputField) => {
            inputField.value = "";
        });
        document.getElementById("errorDisplay").textContent = "";
        document.getElementById("averageAmount").textContent = "";
        document.querySelector("#outputTable tbody").innerHTML = "";
        formSubmitted = false; // Reset the form submission flag
    }

    function clearError() {
        document.getElementById("errorDisplay").textContent = "";
    }
<form id="userInputForm">
    <label for="input1">Input 1:</label>
    <input type="text" id="input1"><br>

    <label for="input2">Input 2:</label>
    <input type="text" id="input2"><br>

    <label for="input3">Input 3:</label>
    <input type="text" id="input3"><br>

    <button type="button" onclick="displayUserInput()">Submit</button>
    <button type="button" onclick="clearInputs()">Clear</button>
</form>

<table id="outputTable">
    <tbody></tbody>
</table>

<p id="averageAmount"></p>

<div id="errorDisplay"></div>

3

Answers


  1. To prevent any rows from being added if any input is invalid you need to first loop over all the inputs and make sure they are all valid and only then add any rows. You can store the values in a temporary array which you can use later when adding rows.

    let formSubmitted = false;
    
    function displayUserInput() {
        if (formSubmitted) {
            return; // Don't add more rows if the form has already been submitted
        }
    
        let total = 0;
        const table = document.querySelector("#outputTable tbody");
        const inputs = ["Input 1", "Input 2", "Input 3"];
        const errorDisplay = document.getElementById("errorDisplay");
        errorDisplay.textContent = ""; // Clear any previous error messages
    
        let hasInvalidFields = false;
    
        const values = inputs.map((inputLabel, index) => {
            if (hasInvalidFields) return null; // Return if previous fields are invalid
    
            const inputField = document.querySelector(`#input${index + 1}`);
            const value = Number(inputField.value);
    
            if (isNaN(value)) {
                hasInvalidFields = true;
                errorDisplay.textContent = `Invalid input for ${inputLabel}. Please enter a number.`;
    
                // Automatically clear the error after 3 seconds (3000 milliseconds)
                setTimeout(() => {
                    errorDisplay.textContent = "";
                }, 3000);
    
                return null;
            }
    
            total += value;
            return value;
        });
    
        if (!hasInvalidFields) {
            inputs.forEach((inputLabel, index) => {
                const row = table.insertRow();
                row.insertCell(0).textContent = inputLabel;
                row.insertCell(1).textContent = values[index];
            });
    
            const average = total / inputs.length;
            document.getElementById("averageAmount").textContent = `Average Amount: ${average}`;
            formSubmitted = true; // Mark the form as submitted
        }
    }
    
    function clearInputs() {
        const inputFields = document.querySelectorAll("input[type='text']");
        inputFields.forEach((inputField) => {
            inputField.value = "";
        });
        document.getElementById("errorDisplay").textContent = "";
        document.getElementById("averageAmount").textContent = "";
        document.querySelector("#outputTable tbody").innerHTML = "";
        formSubmitted = false; // Reset the form submission flag
    }
    
    function clearError() {
        document.getElementById("errorDisplay").textContent = "";
    }
    <form id="userInputForm">
        <label for="input1">Input 1:</label>
        <input type="text" id="input1"><br>
    
        <label for="input2">Input 2:</label>
        <input type="text" id="input2"><br>
    
        <label for="input3">Input 3:</label>
        <input type="text" id="input3"><br>
    
        <button type="button" onclick="displayUserInput()">Submit</button>
        <button type="button" onclick="clearInputs()">Clear</button>
    </form>
    
    <table id="outputTable">
        <tbody></tbody>
    </table>
    
    <p id="averageAmount"></p>
    
    <div id="errorDisplay"></div>
    Login or Signup to reply.
  2. You’ll want to use the HTMLInputElement: checkValidity() method on the keyUp event on the text inputs. You’ll want to put the type on the HTML input and this will interact w checkValidity().

    Login or Signup to reply.
  3. I don’t get your requirements 100%, but here is an example that uses the submit event to insert rows. The form will only submit if all input elements have a number. I run through the list of elements/inputs and insert a row for each. Lastly I use reset() on the form to clear all input elements.

    I hope that it is useful somehow.

    const table = document.querySelector("#outputTable tbody");
    
    document.forms.userInputForm.addEventListener('submit', e => {
      e.preventDefault();
      [...e.target.elements].forEach(input => {
        const row = table.insertRow();
        row.insertCell(0).textContent = input.value;
        row.insertCell(1).textContent = input.value;
      });
      e.target.reset();
    });
    <form name="userInputForm">
      <label for="input1">Input 1:</label>
      <input type="number" id="input1" name="input1" required><br>
    
      <label for="input2">Input 2:</label>
      <input type="number" id="input2" name="input2" required><br>
    
      <label for="input3">Input 3:</label>
      <input type="number" id="input3" name="input3" required><br>
    
      <button type="submit">Submit</button>
      <button type="button">Clear</button>
    </form>
    
    <table id="outputTable">
      <tbody></tbody>
    </table>
    
    <p id="averageAmount"></p>
    
    <div id="errorDisplay"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search