How should I go about this html form with Javascript


Tags: javascript,html,css,forms

Problem :

I have a couple questions and problems that I need some help on. I am working on a basic order form mock up. I am trying to make it look similar to Example Form I need it to follow these three following constraints;

  1. upon clicking the 'order' button provide an error message if the client has not filled in any of the required fields (be specific with my error messages citing which box is in error).
  2. upon clicking the 'order' button provide a different message if they have correctly filled in the required information ( "Thank You, #firstname #lastname, for your order. Your total is $xxxxx).
  3. upon clicking the 'clear' button clear the boxes on the form, I need to be able to do this by writing my own script.

So far I have the layout almost complete. I am a little confused on how to lessen up the padding between the actual fields and the form legend border. I am also having trouble getting the form to reset due to using two different forms in order to achieve the border for both. Is their a way to call two forms via a document.getElementById("myForm" & myForm1").reset() I know this is wrong just figured it was easiest way to word it. The other problem I am having is getting my function to go through and check that their is a response for each input and if not specify where the error is and then if their is no error it reports back what the total amount is by multiplying the price and quantity and then states their first name and last name. Below I will post my HTML, CSS, and JS. If somone could take the time to help me out I would greatly appreciate it. ----Fixed the reset and got it to call both forms-----

<!DOCTYPE html>
<html>

<head>
 <link rel="stylesheet" href="styles.css">  
    <h1>JS Order Form</h1>
</head>
<body>

<script src="script.js"> <!--links js -->
</script>


<form id="myForm">
 <fieldset>
  <legend>Personal Information:</legend>
 First Name: <input type="text" id="field1" name="fname"><br>
 Last Name: <input type="text" id="field2" name="lname"><br>

 </fieldset>
</form>

<table style="width:100%">
        <table align="right">
        <table border="1">  
  <tr>
    <td>Product</td>
    <td>Price</td>      

  </tr>
  <tr>
    <td>Widget 1</td>
    <td>$5</td>     

  </tr>
  <tr>
    <td>Widget 2</td>
    <td>$10</td>        

  </tr>
</table>

<form id="myForm1">
 <fieldset>
  <legend>Order Info:</legend>
  Price: <input type="text" id="field3" name="pname"><br>
  Quantity: <input type="text" id="field4" name="qname"><br>

 </fieldset>
</form>
<div align="center">
<input type="button" onclick="myFunction()" value="Clear">
<input type="button" onclick="myFunction1()" value="Order">
</div>



</body>
</html>
 h1 {
    text-align: center; 
}

form {
    text-align:center;

}

table {
    width:250px;
    margin: 0 auto;
    text-align: center;
}

fieldset {
    padding: 10px;
    margin: 10px;
    border-spacing: 5px;
}
function myFunction() {
        document.getElementById("myForm").reset();  //grabs form and clears entrys
    }   

    //function myFunction1() 
    // {
      //   var field1 = document.getElementById("field1").value.trim(); //checks length of first name
     //    var field2 = document.getElementById("field2").value.trim(); //checks length of last name
      //   if ( field1.length == 0 || field2.length == 0)  // if they are set to 0 then report alert
      //   {
     //       alert("Please Fill In Form Correctly");
      //   } 
      //   else                                          // if filled in report this following alert
      //   {
     //       alert("Thank You for Submitting");
     //   }
     //}


    function myFunction1()
    {
      var field1 = document.getElementById("field1").value.trim();
     var field2 = document.getElementById("field2").value.trim();
     var field3 = document.getElementById("field3").value.trim();
      var field4 = document.getElementById("field4").value.trim();
    if ( field1.length == 0)
     {
            alert("Please fill in your First Name");
            return false;
     }
      else if ( field2.length == 0)
     {
            alert("Please fill in your Last Name");
            return false;
     }
      else if ( field3.length == 0)
     {
            alert("Please fill in the Price")
            return false;
     }
     else if ( field4.length == 0)
     {
            alert("Please fill in the Quantity")
            return false;
     }
    else 
    {
    alert("Thank you for submitting your Order")
    }
    }


Solution :

  1. For showing error messages, avoid using alert. It is not a good way. Rather keep some hidden text with the message and just control its visibility depending on the user's input. Like:

    <span id="field1Error" style="display:none">Please fill in your First Name</span>

In JS:

if(field1.length == 0){
    document.getElementById('field1Error').style.display= 'block';
}
else{
    document.getElementById('field1Error').style.display= 'none';
}
  1. For showing a confirmation also, you can use the above method. Just create your message in JS by gathering values from the fields and put it in a div which is already in the page.

    <div id="confirmMessage"></div>

In JS:

var content= 'Thank you '+ field1.value+ ' '+ field2.value+ ' for your order. Your total is '+ 
    parseInt(field3.value)* parseInt(field4.value)+ '.'
document.getElementById('confirmMessage').innerHTML= content;
  1. The reset() works good. If you want to change this then you can iterate over the fields of the form and clear them manually.

I hope this helps. Please ask if you have any doubts.

Edit: To display a combined alert, use flags to keep track of valid and invalid fields and use if instead of nested if else if blocks.

Change required:

function myFunction1()
{
  var field1 = document.getElementById("field1").value.trim();
  var field1Valid= true;
 var field2 = document.getElementById("field2").value.trim();
var field2Valid= true;
 var field3 = document.getElementById("field3").value.trim();
var field3Valid= true;
  var field4 = document.getElementById("field4").value.trim();
var field4Valid= true;
if ( field1.length == 0)
 {
        field1Valid= false;
 }
 if ( field2.length == 0)
 {
        field2Valid= false;
 }
 if ( field3.length == 0)
 {
        field3Valid= false;
 }
 if ( field4.length == 0)
 {
        field4Valid= false;
 }
var formValid= field1Valid && field2Valid && field3Valid && field4Valid; //true if all fields are valid else false
if( !formValid){
    var alertMessage= 'Please fill ';
    if( !field1Valid){ alertMessage+= 'First Name'; }
    if( !field2Valid){ alertMessage+= 'Last Name'; }
    if( !field3Valid){ alertMessage+= 'Price'; }
    if( !field4Valid){ alertMessage+= 'Quantity'; }
    alert(alertMessage);
    return false;
}
else{
     var alertMessage= 'Thanks for the order '+ field1+ ' '+ field2+ '. Your total is '+ String(parseInt(field3) * parseInt(field4) )+ '.';
    alert(alertMessage);
    return true;
}


}

    CSS Howto..

    Why is Nexus 4 (using Chrome for Android) showing window size as 384x519 but screenshot shows 768x1038?

    How to make last element of second level of menu to drop up?

    How to float: top?

    Creating a javascript notification plugin: How to align absolutely positioned divs on top of each other

    How to use nested p tags in CSS and Bootstrap boxes?

    How do I change image on hover of that the img is in - in jQuery?

    How can I allow resizable() to increase size beyond initial size?

    CSS: How can I stop the horizontal navigation links from shiningthrough the floating cart when it's accordioned down?

    How to programmatically download all contents of webpage, not only the source code in Java

    css: How to add blank space under a sprint element

    How to change css file of bx-slider, multiple sliders on a page [closed]

    How to apply this sidebar to all pages using CSS?

    how to use namespaces in css?

    Responsive menu show and hide on click

    How to view CSS/HTML in GUI?

    Button element styled with CSS is not showing the background-image in IE6

    how to use bootstrap's modal dialog only, instead of the whole bootstrap.css to aviod conflicting with my own css

    how to change the div background image in mouse over [duplicate]

    How to change default message “Please enter a value with a valid mimetype.” for HTML file input

    How can we cache inline SVG in Browsers?

    how to trigger “onMouseOut” from click

    How to use vertical align in bootstrap

    How can I turn the page's font color to green when a button is clicked

    How do I use the Bootstrap form select css with a Rails model?

    How to override a style of a specific Joomla module?

    Bootstrap 4 and user details - how to do the “bootstrap” or correct way?

    How to do line animation using CSS and SVG

    How at least approximately imitate col-md-1.5?

    How to make a diagonal css gradient without the colors blending together(a sharp color change) that's displaced 70% to the right?

    How to avoid bloating pages with divs?