Paul Davis
Paul Davis

Reputation: 525

Use JS to determine if all form fields are filled and correctly

*Edit: Fixed so that all inputs are now validated on one form. However, I can only add one variable to check if blank, as soon as I add more, none of the submit functions work. I have been trying multiple things.

function validateForm() {
  var inputVelocity = document.getElementById("dzCalculator").inputVelocity.value;
  var inputYellowPhase = document.getElementById("dzCalculator").inputYellowPhase.value;
  var inputRedPhase = document.getElementById("dzCalculator").inputInterPhase.value;
  var inputReactionTime = document.getElementById("dzCalculator").inputReactionTime.value;
  if(inputVelocity === "" && inputYellowPhase === "" && inputRedPhase === "" && inputReactionTime === ""){
    alert("Input all fields to calculate.");
    return false;
  }
}

I have checked the HTML matches - it does. But I found I could not use onsubmit="return validateForm" as this wouldn't work at all.

This is only 4 of the form values, there are seven all up. But when I can get the four working, I can get them all working.

How can I use JS to make sure that no input is left blank or empty? I already have made it so that it will only accept numbers and decimal points. So no one can add an incorrect field. But currently, they can leave a field blank which means my calculator generates a NaN response.

Also, how can I make sure one of my fields can not accept a number greater than 1 or less than 0. I tried min="0" max="1" in the input tag, but because I have removed spinners, this doesn't work.

So, in summary, I am looking to make sure when a button is clicked that all the form sections are filled in and that one of the fields doesn't accept a number greater that 1 or less than zero.

Upvotes: 1

Views: 5696

Answers (4)

Julian Olivier
Julian Olivier

Reputation: 31

This works for me. You can use it, style it however you want or not. You do need JQuery. It has powerful selectors.

<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
    
    body{
        font-size: 12px;
    }

    .main-container{
        display: flex;    /* DO NOT CHANGE */
        height: 100vh;    /* DO NOT CHANGE */
        width: 100%;      /* DO NOT CHANGE */
    }

    .c-message{
        display: flex;    /* DO NOT CHANGE */
        position: fixed;  /* DO NOT CHANGE */
        top: 0px;         /* DO NOT CHANGE */
        left: 0px;        /* DO NOT CHANGE */
        width: 100%;      /* DO NOT CHANGE */
        height: 100%;     /* DO NOT CHANGE */
    }

    .c-msgbox{
        padding: 30px;
        text-align: center;
        margin: auto; /* DO NOT CHANGE */
        background-color: #e4e4e4;
        border-radius: 4px;
        border: 1px solid #adadad;
        -webkit-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
        -moz-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
        box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.40);
    }

    .standerd-button2{
        border: none;
        font-family: arial,helvetica,clean,sans-serif;
        font-size: 10px;
        font-weight: 600;
        color: white;
        background: #1A709F;
        padding: 3px;
        text-align: center;
        vertical-align: middle;
        -webkit-border-radius: 3px;
        width: max-content;
        min-width: 50px;
        margin: 2px;
    }

    .standerd-button2:hover{
        background: crimson;
        cursor: default;
    }

    .f-table {
        display: table;
        width: max-content;
        padding: 5px;
        border-spacing: 2px;
    }

    .f-tablerow {
        display: table-row;
    }    

    .f-tablecell{
        display: table-cell;
    }    

    .label-cell-r{
        text-align: right;
    }
    
    .dd-required{
        margin: auto;
        color: red;
    } 

    input, select{
        border: 1px solid lightgrey;
    }   


</style>
<script type="text/javascript" src="JQuery.js"></script>
</head>
<body>
<div class="main-container">
    <div>
        <form id="f1" name="f1">
            <div class="f-table">
                <div class="f-tablerow">
                    <div class="f-tablecell label-cell-r">
                        <label for="firstname">First Name</label>
                    </div>
                    <div class="f-tablecell input-cell">
                        <input id="firstname" name="firstname" type="text" data-er="First Name"/>
                        <span class='dd-required'>*</span>
                    </div>
                </div>
                <div class="f-tablerow">
                    <div class="f-tablecell label-cell-r">
                        <label for="lastname">Last Name</label>
                    </div>
                    <div class="f-tablecell input-cell">
                        <input id="lastname" name="lastname" type="text" data-er="Last Name"/>
                        <span class='dd-required'>*</span>
                    </div>
                </div>
                <div class="f-tablerow">
                    <div class="f-tablecell label-cell-r">
                        <label for="company">Company</label>
                     </div>
                    <div class="f-tablecell input-cell">
                        <select id="company" name="company" data-er="Company Name">
                            <option value="0"> - Select Comapny - </option>
                            <option value="1">Company 1</option>
                            <option value="2">Company 2</option>
                            <option value="3">Company 3</option>
                            <option value="4">Company 4</option>
                        </select>
                        <span class='dd-required'>*</span>
                    </div>
                </div>            
            </div>
            <input id="b1" type="submit" value="Submit" />
        </form>
    </div>
<div>
<script type="text/javascript">

    $.fn.CustomAlert = function (options, callback) {
        var settings = $.extend({
            message: null,
            detail: null,
            yesno: false,
            okaytext: null,
            yestext: null,
            notext: null
        }, options);

        var frm = "";
        detail = "<b>" + settings.detail + "</b>";
        message = "<b>" + settings.message + "</b>";
        if (settings.detail === null) {
            detail = "";
        };

        frm = frm + message + "<div style='text-align: left; margin-top: 15px; margin-bottom: 15px;'>" + detail + "</div>";

        if (settings.yesno === false) {
            frm = frm + "<input id='ok' type='button' value='" + settings.okaytext + "' class='standerd-button2' />";
        } else {
            frm = frm + "<div><input id='yes' type='button' value='" + settings.yestext + "' name='yes' class='standerd-button2' />" +
                        "<input id='no' type='button' value='" + settings.notext + "' name='no' class='standerd-button2' /></div>";
        };

        var frmesg = "<div id='cmessage' name='cmessage' class='c-message'>" +
                     "<div class='c-msgbox'>" +
                     "<form>" + frm + "</form>" +
                     "</div>" +
                     "</div>";

        $(".main-container").append(frmesg);

        if (!settings.yesno) {
            $("#cmessage #ok").click(function () {
                $("#cmessage").remove();
                callback(false);
            });
        } else {
            $("#cmessage #yes").click(function () {
                $("#cmessage").remove();
                callback(true);
            });
            $("#cmessage #no").click(function () {
                $("#cmessage").remove();
                callback(false);
            });
        };
    };

    $.fn.JsFormCheck = function () {
        var MessData = "";
        this.find('select, input').each(function () {
            if ($(this).attr("data-er")) {
                m = $(this).attr("data-er");
                switch ($(this).get(0).tagName) {
                    case "INPUT":
                        if ($(this).val().length === 0) {
                            MessData = MessData + "- " + m + "<br>";
                            $(this).css('border-bottom', '2px solid green');
                        };
                        break;
                    case "SELECT":
                        if ($(this).val() === "0") {
                            MessData = MessData + "- " + m + "<br>";
                            $(this).css('border-bottom', '2px solid green');
                        };
                        break;
                };
            };
        });

        if (MessData.length > 0) {
            MessData = "<b>" + MessData + "</b>";
            x = $().CustomAlert({message: "<b>Please fill in the following required fields to continue.</b>",
                               detail: MessData,
                               okaytext: "Close",
                               yesno: false});
            return true;
        } else {
            return false;
        };
    };

    $('#f1 #b1').click(function(event){
        event.preventDefault();
        Error = $("#f1").JsFormCheck();    
        if(Error === false){
            null;
            //Do Something
        };  
    });
</script>
</body> 

Upvotes: 0

Ranjeet Eppakayala
Ranjeet Eppakayala

Reputation: 3028

Reference: javascript_form_validation

Depends when would you like to validate form fields

For example: Form validation on submit

function validateForm() {
  var x = document.forms["myForm"]["fname"].value;
  if (x == "") {
    alert("Name must be filled out");
    return false;
  }
}
<html>

<body>
  <form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
    Name: <input type="text" name="fname">
    <input type="submit" value="Submit">
  </form>
</body>

</html>

Give name to your form using name attribute such as <form name="myForm" ..>

Then using document.forms["myForm"] you can have access to your form

There you can validate your input fields value. return true if validates

Upvotes: 0

Sante
Sante

Reputation: 349

Can you please give more detail about how your form is in multiple places?

For input I think you need to use step attribute

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#step

Upvotes: 0

Abdelrahman Hussien
Abdelrahman Hussien

Reputation: 505

there are 2 options for this.

  • You can select all the inputs (inside the form tag) using querySelector and check the value of each input by looping through them.
  • use this trick selector to get all the invalid inputs document.querySelectorAll('input:not([value]):not([value=""])'); replace input with more precise selector.

Upvotes: 2

Related Questions