Jump to content

Simple Form And Calculation


jacko_162

Recommended Posts

I want a simple form with 1x Input field;

 

<form>
<input name='Volume' type='text' />
<input type='hidden' name='value' value ='850' />
<input type='submit' name='Calculate' />
</form>

 

the input will be a number only, if the user inputs 5 for example:

 

i want it to perform the following maths:

 

5x$value (5x850) and display the result when the user clicks submit.

 

Also if the user submits a number bigger than 320000 can we output an error message?

 

how would i go about this using simple js ? i have no idea how to code js at the moment.

Link to comment
https://forums.phpfreaks.com/topic/270204-simple-form-and-calculation/
Share on other sites

Here's a little example with jQuery.

Demo: http://xaotique.no-ip.org/tmp/14/

 

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   <head>
       <title>Xaotique</title>
       <meta http-equiv="content-type" content="text/html;charset=utf-8" />
       <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
       <script type="text/javascript" src="script.js"></script>

       <style type="text/css">
           body
           {
               font-size: 12px;
           }

           input
           {
               width: 150px;
           }

           #result
           {
               color: #000099;
               font-size: 14px;
           }
       </style>
   </head>

   <body>
       <b>Input:</b> <input type="text" id="myval" /> <b>Multiplied by 5:</b>
       <span id="result"><span style="color: red;">Javascript Not Enabled</span></span>
   </body>
</html>

 

script.js

$(document).ready(function()
{
   // Value Default Vars
   var min = 0, max = 320000, defaultValue = 850;

   // Set Defaults
   $("#myval").val(defaultValue).keyup();

   // Calculate When Changed
   $("#myval").keyup(function()
   {
       // Parse Inputted Value
       var value = parseInt($("#myval").val());

       // Check If Low, High, or Invalid
       if (value < min || isNaN(value * 5))
           value = min;
       else if (value > max)
           value = max;

       // Show Result
       $("#myval").val(value);
       $("#result").html(value * 5);
   });

   // Backup If Using Paste
   $("#myval").change($("#myval").keyup());
});

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.