I'm trying to create comparison/validation of two numbers for retrieving the right number from the database.
I'm doing using PHP, HTML and retrieve the details of weight from XAMPP database to compare with user input.
I'm using type='number' so that user can only input digits.
HTML FORM
<form action="" method="POST" onSubmit= "return Validator_edit(this)">
<table class="midTable" align="center" cellpadding="3" cellspacing="3" enctype="multipart/form-data" >
<tr>
<tr>
<th align="right" >Weight:</th>
<td><input type="number" size="20" name="weight" id="weight" value="<?php echo $weight ?>" disabled="disabled"> * Weight that you have set previously <br/></td>
</tr>
<tr>
<th align="right" >Progress:</th>
<td><input type="number" name="progress" value="<?php echo $progress ?>" id="progress" >
* NOTE : Progress must NOT exceed the weight you have set .</strong><br></h3></td>
</tr>
<tr >
<td colspan='2' align='center'><input type="submit" value="update" name="submit" />
</tr>
</table>
</form>
Validation form
<script type="text/javascript" language="javascript">
function Validator_edit(frm){
if (frm.progress.value=="")
{
alert("progess must not be empty");
frm.progress.focus();
return false;
}
if (frm.progress.value > frm.weight.value )
{
alert(" You have exceed the weight.");
frm.progress.focus();
return false;
}
}
</script>
For some reason, it is able to validate "some" numbers. For example: I've set:
Weight = 50
logically progress under 50 will be able to be validated and return true.
However, it fails on 3, 4, 5, 6, 7, 8, 9, even though these numbers are less than 50.
How do I solve this problem?
Your numbers might be in string forms. You might try using a function such as Number(); in JavaScript and pass it through that, just to make sure, typeof your form progress values are number.
Maybe, try something similar to:
<script type="text/javascript" language="javascript">
function Validator_edit(frm){
if (frm.progress.value=="")
{
alert("progess must not be empty");
frm.progress.focus();
return false;
}
if (Number(frm.progress.value) > Number(frm.weight.value) )
{
alert(" You have exceed the weight.");
frm.progress.focus();
return false;
}
}
</script>
Or you might pass it through a regex, maybe similar to:
function is_number(form_progress_number) {
return /^\d+$/.test(form_progress_number);
}
This link might help you.
Related
Type apple in the input whose name is goods,and type 9 in the input whose name is price,and click submit,now confirm window pop up,whatever your click yes or no,the data will send to price.php.
My expectation:
when you click yes ,the data will send to price.php,
when you click no ,the data will not send to price.php,what's wrong for my js?
ob = document.getElementById("submit");
function check(){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
exit;
}
}
}
ob.addEventListener("click",check,false);
<form action="price.php" method="post">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
The price.php is simple.
<?php
var_dump($_POST);
?>
The exit below can't prevent form data from sending to price.php.
if(flag){
return true;
}else{
exit;
}
It is no use either to change exit; into return false;.
It is no use either to change js into below.
ob = document.getElementById("submit");
function check(){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
exit;
}
}
}
ob.addEventListener("submit",check,false);
The traditional way is same as The KNVB did,the key point is <form action="price.php" method="post" onsubmit="return check()"> ,to bind form's attribute onsubmit with function check.
DOM0 level event way,almost the same like the traditional way.
<html>
<body>
<form action="price.php" method="post" id="form">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
var ob = document.getElementById('submit');
ob.onclick =function(){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
return false;
}
}
}
</script>
</body>
</html>
What OP expect is the DOM2 level event way.
<html>
<body>
<form action="price.php" method="post" id="form">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
var ob = document.getElementById('submit');
function check(event){
console.log(ob.type);
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
ob.submit();
return true;
}else{
event.preventDefault();
return false;
}
}
}
ob.addEventListener("click",check);
</script>
</body>
</html>
The key points in DOM2 level event way are:
1.when flag is true
if(flag){
ob.submit();
return true;
}
2.when flag is false
else{
event.preventDefault();
return false;
}
This is my solution:
<html>
<body>
<form action="price.php" method="post" onsubmit="return check()">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
function check()
{
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
return false;
}
}
}
</script>
</body>
</html>
I tested it on Edge, IE11, Firefox, chrome browser, it works.
I found another solution:
<html>
<body>
<form action="price.php" method="post" id="form">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
var ob = document.getElementById('form');
function check(event){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
ob.submit();
return true;
}else{
event.preventDefault();
return false;
}
}
}
ob.addEventListener("submit",check);
</script>
</body>
</html>
A couple of things about the code:
exit - I've never seen before - is it javascript?
document.getElementById('price').value - returns a string - you should parse it (to a number) before comparing.
Use onsubmit="" attribute of the form - return true to allow form submission, false to block submission.
window.confirm already returns a boolean, just return that (instead of if statement).
Here's a bare-bones example:
function validate() {
const price = parseFloat(document.getElementById('price').value)
if (price < 10) {
return window.confirm("Are your sure the price is less than 10 ?")
}
return true // <- otherwise allow form submission
}
<form action="price.php" method="post" onsubmit="return validate()">
<input type="text" id="price" name="price">
<input type="submit" id="submit" value="submit">
</form>
Also, in general, try to condense your problem to the minimum code required to reproduce an issue.
I'm working on creating a page in which someone could calculate their Net Worth by entering various values. The input text will show a .00 afterwards if no decimal point is added in. I'm having troubles in getting a sum of all of the values.
Java:
<script type="text/javascript"><!--
function updatesum() {
document.form.TotalAssets.value = (document.form.CashOnHand.value -0) + (document.form.CashInChecking.value -0);
}
//-->
</script>
HTML:
<input type="text" onblur="if(this.value.indexOf('.')==-1)this.value=this.value+'.00'" onchange="format(this); updatesum()" onkeyup="format(this)" maxlength="11" value="0" name="CashOnHand" /></td>
</tr>
<tr>
<td><strong>Cash in Checking</strong></td>
<td>$
<input type="text"
onblur="if(this.value.indexOf('.')==-1)this.value=this.value+'.00'" onchange="format(this); updatesum()" onkeyup="format(this)" maxlength="11" value="0" name="CashInChecking" /></td>
</tr>
<tr>
<td align="right"><strong>Total Assets</strong></td>
<td>$<input name="TotalAssets" readonly ></td>
</tr>
It's not giving me a sum of the the values that I'm adding.
I think this is because document.form is undefined, but this one works:
function updatesum() {
var hand = parseFloat(document.forms[0].CashOnHand.value);
var checking = parseFloat(document.forms[0].CashInChecking.value);
document.forms[0].TotalAssets.value = hand - checking;
}
I am a Computing teacher trying to stay one step ahead of my pupils whom are working on a assessment to with validating web forms using HTML and JavaScript. So far, I have managed to do the following but can no longer move forward:
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+='You must enter your name';
document.ExamEntry.name.focus();
document.getElementById("name").style.color="#FF0000";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+=' You must enter the subject';
document.ExamEntry.subject.focus();
document.getElementById("subject").style.color="#FF0000";
result = false;
}
if (document.ExamEntry.examnumber.value=="") {
msg+=' You must enter the examination number';
document.ExamEntry.examnumber.focus();
document.getElementById("examnumber").style.color="#FF0000";
result = false;
}
if(document.getElementById("examnumber").value.length!=4)
{
msg+='You must have exactly 4 digits in the examination number textbox';
document.ExamEntry.examnumber.focus();
document.getElementById("examnumber").style.color="#FF0000"
result = false;
}
function checkRadio() {
var user_input = "";
var len = document.ExamEntry.entry.length;
var i;
for (i=0;i< len;i++) {
if (document.ExamEntry.entry[i].length.checked) {
user_input = document.ExamEntry.entry[i].value;
break;
}
}
if (msg==""){
return result;
}
else
{
alert(msg);
return result;
}
}
function resetForm()
{
document.getElementById('ExamEntry').reset();
document.getElementById("name").style.color="#000000";
document.getElementById("subject").style.color="#000000";
document.getElementById("examnumber").style.color="#000000";
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name='ExamEntry' method='post' action='success.html'>
<table width='50%' border='0'>
<tr>
<td id='name'>Name</td>
<td><input type='text' name='name' /></td>
</tr>
<tr>
<td id='subject'>Subject</td>
<td><input type='text' name='subject' /></td>
</tr>
<tr>
<td id='examnumber'>Examination Number</td>
<td><input type='text' name='examnumber'></td>
</tr>
<tr>
<td id='entry'>Level of Entry</td>
<td><input type='radio' name='entry' value='gcse'>GCSE<BR></td>
<td><input type='radio' name='entry' value='as'>AS<BR></td>
<td><input type='radio' name='entry' value='a2'>A2<BR></td>
</tr>
<tr>
<td><input type='submit' name='Submit' value='Submit' onclick='return (validateForm());'></td>
<td><input type='reset' name='Reset' value='Reset' onclick=' (resetForm());'></td>
</tr>
</table>
</form>
</body>
What I want to do and what I am trying to do are two different things and it's now hit the point where I am banging my head against a brick wall.
What I WANT to do is be able to:
Extend the Javascript code to make sure that the user’s examination number is exactly 4 digits.
Add a set of radio buttons to the form to accept a level of entry such as GCSE, AS or A2. Write a function that displays the level of entry to the user in an alert box so that the level can be confirmed or rejected.
Can anyone help me before I totally lose the plot?
It's been a long time I have tried pure JS. It's a pleasure to try it out anytime though. So, someone's lukcy and I had some free time. I am a very tiny bit OCD when it comes to coding and I ended up cleaning a lot of your code, such as
Always enclose HTML attributes in double quotes - not a hard rule though.
Always close the input attributes - /> - not a hard rule though.
Define your elements and resue where needed in JS
Alwayst try and keep your JS separate from HTML - it's a good practice.
And follow the good old basics
As a result, here we go:
Demo: Fiddle
HTML:
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="#">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examnumber">Examination Number</td>
<td><input type="text" name="examnumber" /></td>
</tr>
<tr>
<td id="entry">Level of Entry</td>
<td><input type="radio" name="entry" value="gcse" />GCSE<BR></td>
<td><input type="radio" name="entry" value="as" />AS<BR></td>
<td><input type="radio" name="entry" value="a2" />A2<BR></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" onclick="resetForm();"></td>
</tr>
</table>
</form>
JS:
var form = document.forms['ExamEntry'];
var iName = form.elements['name'];
var iSubject = form.elements['subject'];
var iExamNumber = form.elements['examnumber'];
var iLevel = form.elements['entry'];
function validateForm() {
var result = true;
var msg = "";
if (iName.value=="") {
msg+='You must enter your name';
iName.focus();
iName.style.color="#FF0000";
result = false;
} else if (iSubject.value=="") {
msg+=' You must enter the subject';
iSubject.focus();
iSubject.style.color="#FF0000";
result = false;
} else if (iExamNumber.value=="" || !/^\d{4}$/.test(iExamNumber.value)) {
msg+=' You must enter a valid examination number';
iExamNumber.focus();
iExamNumber.style.color="#FF0000";
result = false;
} else if(!checkEntry()) {
msg+=' You must select a level';
result = false;
} else {
var cfm = confirm("You have selected " + checkEntry() + ". Are you sure to punish yourself?");
if (!cfm) {
result = false;
}
}
if (!result && msg != "") alert (msg);
return result;
}
function checkEntry() {
for (var i=0; i<iLevel.length; i++) {
if (iLevel[i].checked) {
return iLevel[i].value.toUpperCase();
}
}
return false;
}
function resetForm() {
form.reset();
iName.style.color="#000000";
iSubject.style.color="#000000";
iExamNumber.style.color="#000000";
}
form.onsubmit = validateForm;
form.onreset = resetForm;
First you added the function checkRadio inside of function validateForm
Also, this line
if(document.getElementById("examnumber").value.length!=4)
actually points to this piece of html
<td id='examnumber'>Examination Number</td>
The td element can't hold values... You need to change the line to this:
if (document.ExamEntry.examnumber.value.length!=4) {
This jsfiddle should help you out...
I am trying to use a simple function of javascript that was intended to be used with a SELECT dropdown with single digits, but now I need to use it for when visitors type in a value with decimal points. I am getting a NaN with the current javascript even when I type in 30 or any number. Any suggestions on how to get my total?
JAVASCRIPT:
$(function () {
$('.DoPricing').change(function () {
var total = 0;
$('.DoPricing').each(function () {
total += parseInt($(this).val());
});
$('#TotalPrice').html('$' + total);
});
});
HTML:
<form action="myactionpage.php" method="POST">
<table>
<tr>
<td>How much will you be paying today?</td>
<td>$<input type="text" name="howmuch" id="howmuch" placeholder="0.00" class="DoPricing"></td>
</tr>
<tr>
<td><div class="totalbox">Total Amount Due Today: <strong><span id="TotalPrice">$0.00</span></strong></div>
</td>
</tr>
<tr><td><input type="submit" id="submit" name="submit" value="Submit Payment" class="submitbut" /></td>
</tr>
</table>
</form>
Try this:
$(function () {
$('.DoPricing').on("keyup",function () {
var total = 0;
$('.DoPricing').each(function () {
total += parseFloat($(this).val()) || 0;
});
$('#TotalPrice').html('$' + total);
});
});
This accepts decimals now, here is the demo
Your basic example works for me. I'm guessing there are other elements on the page with class, but that don't necessarily have values, and that you'd like them to default to zero. When an input has no value, .val() returns the empty string, and parseInt('', 10) returns NaN, not 0, so you're not getting what you want.
This is very simple to fix:
total += parseInt($(this).val()) || 0;
Demo: http://jsfiddle.net/mattball/2rgku
I assume you want decimals as well but you're using parseInt instead of parseFloat and if you're using decimals (because it's money) then you should use toFixed. In the following code I assume the user will use the . as a decimal symbol and there should be only one . in the value (no thousands separator).
In your for each you convert a perfectly good usable this to a jQuery object only to get the value. I've changed $(this).val() to this.value so the conversion isn't needed.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="jquery-1.9.0.js"></script>
</head>
<body>
<form action="myactionpage.php" method="POST">
<table>
<tr>
<td>How much will you be paying this morning?</td>
<td>$<input type="text" name="howmuch" id="howmuch" placeholder="0.00" class="DoPricing"></td>
</tr>
<tr>
<td>How much will you be paying this evening?</td>
<td>$<input type="text" name="howmuch" id="howmuch1" placeholder="0.00" class="DoPricing"></td>
</tr>
<tr>
<td><div class="totalbox">Total Amount Due Today: <strong><span id="TotalPrice">$0.00</span></strong></div>
</td>
</tr>
<tr><td><input type="submit" id="submit" name="submit" value="Submit Payment" class="submitbut" /></td>
</tr>
</table>
</form>
<script type="text/javascript">
(function () {
function getValue(el) {
if (el.value === "") { return 0; }
var nr = parseFloat(el.value);
// only 0 to 9 or . and only one . used as decimal symbol
if (/[^0-9.]/.test(el.value) || /.*?\..*?\./.test(el.value)) {
return false;
}
return nr;
}
$('.DoPricing').on("keyup", null, null, function (e) {
var $this = $(this),
val = getValue(this),
total = 0;
if(val!==false){
$this.data("pref",val);
}else{
$this.val($this.data("pref")||"");
}
$('.DoPricing').each(function () {
total += parseFloat(this.value,10)||0;
});
$('#TotalPrice').html('$' + total.toFixed(2));
});
})();
</script>
</body>
</html>
im a bit new using javascript in HTML. I want to validate a HTML script using javascript however what i've written doesn't seem to work. Can anyone tell me where I'm going wrong???
Here is the Javascript:
<script type="text/javascript">
function mandatoryFields()
{
var x=document.forms["add"]["contract_id"].value
if (x==null || x=="")
{
alert("Please Enter the Contract Title");
return false;
}
var x=document.forms["add"]["storydiv"].value
if (x==null || x=="")
{
alert("Please Enter a Sprint");
return false;
}
var x=document.forms["add"]["storydiv"].value
if (x==null || x=="")
{
alert("Please Enter a Story");
return false
}
var x=document.forms["add"]["date1"].value
if ( x=="" || x==null)
{
alert("Please Enter a time");
return false
}
</script>
And here is the corresponding HTML script
<form name="add" action="time-sheet/insert-time-sheet.php" method="post" onsubmit="return mandatoryFields()">
<table width="500" border="0" align="center" cellpadding="2" cellspacing="2">
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td width="150">Select Date:</td>
<td width="336"><input name="date" type="text" value="YYYY-MM-DD" maxlength="100" class="datepick" id="date1" /></td>
</tr>
<tr>
<td>Contract:</td>
<td><SELECT NAME="contract_id" onChange="getSprint(this.value)"><OPTION VALUE=0>--- Select Contract ---<?php echo $options_contract?></SELECT></td>
</tr>
<tr>
<td>Sprint:</td>
<td><div id="sprintdiv"><select name="sprint" >
<option>--- Select Sprint ---</option>
</select></div></td>
</tr>
<tr>
<td>Story:</td>
<td><div id="storydiv"><select name="story">
<option>--- Select Story ---</option>
</select></div></td>
</tr>
<tr>
<td>Dev Time:</td>
<td><input name="dev_time" size="20" onkeyup="ondalikSayiKontrol(this)" /></td>
</tr>
<tr>
<td>PM Time:</td>
<td><input name="pm_time" size="20" onkeyup="ondalikSayiKontrol(this)"/></td>
</tr>
<tr>
<td colspan="2"><table width="182" border="0" align="center" cellpadding="2" cellspacing="2">
<tr>
<td width="68"><input name="Submit" type="submit" id="Submit" value="Add Time Sheet" /></td>
<td width="48"><label>
<input type="reset" name="reset" value="Reset" />
</label></td>
<td width="46"><div align="center">Back</div></td>
</tr>
<input type="hidden" name="day" value="<?php echo $day; ?>" />
<input type="hidden" name="employee_id" value="<?php echo $employee_id; ?>" />
</table></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
</table>
</form>
Thanks in advance!
You're missing the closing brace on the function. If you check the error console on your browser, it will most likely tell you mandatoryFields() is undefined. Adding the closing brace will fix that. You should also return true if none of the validation fails. One last thing is that you re-declare x before each if. Not sure if it produces an error but still should be fixed.
<script type="text/javascript">
function mandatoryFields()
{
var x=document.forms["add"]["contract_id"].value;
if (x==null || x=="")
{
alert("Please Enter the Contract Title");
return false;
}
x=document.forms["add"]["storydiv"].value;
if (x==null || x=="")
{
alert("Please Enter a Sprint");
return false;
}
x=document.forms["add"]["storydiv"].value;
if (x==null || x=="")
{
alert("Please Enter a Story");
return false;
}
x=document.forms["add"]["date1"].value;
if ( x=="" || x==null)
{
alert("Please Enter a time");
return false;
}
return true; // ADD THIS
} // ADD THIS
</script>
Your madatoryFields() function is not returning true when all fields are right.
from here:
If the event handler is called by the onsubmit attribute of the form
object, the code must explicitly request the return value using the
return function, and the event handler must provide an explicit return
value for each possible code path in the event handler function.
Get the right elements and perform a loop on the options inside of sprint and story.
You can use the name of your form and the names of your select boxes to access the elements straight forward.
var x = document.add.contract_id.value;
if(){
... your stuff here
}
You can also access the first form without using its name attribute.
x = document.forms[0].contract_id.value;
For sprint loop through possible options and make your alert then.
x = document.add.sprint;
var selected = false;
for (i = 0; i < x.length; ++i){
if (x.options[i].selected == true)
selected = true;
}
if(!selected){
alert("Select a story please!");
return false;
}
x = document.add.story;
selected = false;
// same procedure
You can also access the elements via getElementByID() and getElementsByTagName(), the latter returns an array of all matched elements.
document.getElementById('storydiv').getElementsByTagName('story')[0];
document.getElementsByTagName('contract_id')[0];
And dont redeclare var x in every validation step.