Javascript form validation isn't working - javascript

I'm writing a form validation script in JavaScript. When the form is submitted, I want it to be validated before going to the next page.
This page is being called from another page using Perl Interchange. Validation is performed for the three fields on the form.
Update: here is the full code:
<FORM ACTION="[process]" name="outofstock_form" METHOD=POST onsubmit="return validate_outofstockform();" >
<INPUT TYPE=hidden NAME="mv_todo" VALUE="return">
<INPUT TYPE=hidden NAME="mv_nextpage" VALUE="outofstock_wish_submit">
<INPUT TYPE=hidden VALUE="[perl scratch session]$which_search;[/perl]" NAME="search_key">
<script type=javascript>
function validate_outofstockform() {
var m = document.forms["outofstock_form"]["email"].value
var e = document.outofstock_form.email.value
var f = document.forms["outofstock_form"]["name"].value
var p = documnet.forms["outofstock_form"]["wish_product"].value
var atpos = e.indexOf("#");
var dotpos = e.lastIndexOf(".");
if (document.outofstock_form.email.value == "") {
alert("The Email field is required.");
return false;
}
if (document.outofstock_form.name.value == "") {
alert("The Name field is required.");
return false;
}
if (document.outofstock_form.wish_product.value == "") {
alert("The Product field is required.");
return false;
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= e.length) {
alert("Please enter a valid e-mail address");
return false;
}
if (f == null || f == "" || f == "First Name") {
alert("Please enter your first name");
return false;
}
if (p == null || p == "" || p == "Product") {
alert("Please enter your first name");
return false;
}
return false;
}
</script>
<br/>
*Fields in bold are required.<br/>
<table cellpadding="1" cellspacing="5" width="360px" border="0">
<tr>
<td><b>Name:</b></td>
<td>
<input type="text" id="name" name="name" size="40">
</td>
</tr>
<tr>
<td><b>E-mail:</b></td>
<td>
<input type="text" id="email" name="email" size="40">
</td>
</tr>
<tr>
<td>Phone:</td>
<td>
<input type="text" name="phone" size="40">
</td>
</tr>
<tr>
<td> State/ Province:</td>
<td>[include pages/ord/widget_state.html]</td>
</tr>
<tr>
<td > Zip/Postal Code:</td>
<td><INPUT TYPE="text" NAME="zip" VALUE="" size="40" maxlength="10"></td>
</tr>
<br/>
<tr>
<td valign="bottom">Country:</td>
<td>[include pages/ord/widget_country_s.html]</td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Salesperson:</td>
<td align=left colspan=2>
<SELECT NAME="salesrep" class="field">
<OPTION VALUE="WEB">(Optional)
[query list=1 prefix=s sql="SELECT id AS username, real_name AS disp_name, everest_id AS int_id FROM employee WHERE sales_ddown = 'Y' AND everest_id != '' ORDER BY real_name"]
<OPTION VALUE="[s-param int_id]"[calc]'[value salesrep]' eq '[s-param int_id]' ? 'selected' : '';[/calc]>[s-param disp_name]
[/query]
</SELECT>
</td>
<INPUT TYPE=hidden NAME="salesperson" VALUE="[s-param username]">
[perl values scratch]
$Scratch->{salesperson} = q{[s-param username]};
[perl]
<tr>
<td colspan="2">
Provide us with the product you are looking for, or the brand and product type
of interest and we will inform you if we find a match.
</td>
<td></td>
</tr>
<tr>
<td><b>Product:</b></td>
<td>
<input type="text" id="wish_product" name="wish_product" size="40" value="">
</td>
</tr>
<tr>
<td>Item Description:</td>
<td>
<textarea name="wish_descrip" rows="2" cols="40"></textarea>
</td>
</tr>
<tr>
<tr>
<td>Brand/Manufacturer Preference:</td>
<td><input type="text" name="wish_man" size="40"></td>
</tr>
<tr>
<td>Product Category :</td>
<td>
<select name="wish_cat">
<option value="" selected>Any Category</option>
[include pages/CATLIST.html]
</select>
</td>
</tr>
<tr>
<td>Is this for a business?:</td>
<td>
<input type="radio" name="option" value="Yes"> Yes
<input type="radio" name="option" value="No"> No<br>
</td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="2"><font size="0px">
We do not sell, rent or otherwise share your information with anyone.<br/>
</font>
</td>
<td></td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" name="Submit" value="Submit" class="button">
</td>
</tr>
</table>
</form>

Make your JavaScript valid (remove part with multiple dashes) and make it return false to avoid sending the form.

It's hard to tell what exactly is causing the problem, because there are several errors in your code.
A couple of pointers:
You're referencing document.outofstock_form, while the form's name is frm.
<//code table> is not valid HTML. Remove it or replace it with an HTML comment (e.g.: <!-- table code: -->).
It's more common to use a regular expression (search here on SO) to validate form input.
If you're sending the input to a server, perform validation on the server as well. Never trust input from the browser.
You never open the <tr> (presumably a copy-paste error).
And finally, but most importantly:
Always look at your browser's JavaScript error console first. This must be your starting point when debugging JavaScript code. It can help you find the problem and if it doesn't, it can help others help you.
Read How to Ask.

Have you debugged your code?
Use tools like Firebug to debug your scripts. Put a breakpoint in the first line of your validation function and then debug it step by step. You will eventually get to the line that's causing your problems.
A suggestion of how to improve your validator
But apart from debugging I would do validation differently. Instead of checking every single aspect of individual fields I'd rather just add a custom attribute to those inputs that need validation and just check whether they match or not. If any fails inform your user about non-valid field...
<input name="SomeName"
validation-expression=".+"
display-name="Required text field"
type="text" />
Using libraries like jQuery would be even more helpful when working with such data because it would be much easier to enumerate these elements and work with their data... I would of course warmly suggest you use jQuery anyway because it will make your code much more cross-browser. It's a simple library with short learning curve but huge benefits.
But using those special attributes would make your validator function universal so it could be used with any element and on any page. All you'd have to do is to put particular validation attributes to your elements.
Just a suggestion of course.

Related

How to send a POST method without refreshing/submitting the page

I am trying to update a specific field in the database, namely "assigned" from the Phone model.
I tried to make a function(setBooleanForCurrentPhone()) in javascript that would change the value of id="assignPhone" from "true" to "false" at the onchange in select.
The problem is that the "assigned" is not changed in database, because I am not submitting anything yet.
Also, I tried to make a button, just to test it, that would call the setBooleanForCurrentPhone() function onclick, but the problem is that
this is submitting the data, the page jumps to another one and I don't get to use the last submit button which calls setBooleanForPhone().
Basically, I want to find a way update that value from dataBase without refreshing/changing the page.
<tr>
<td>Employee id:</td>
<td><input type = "text" th:field="*{id}" readonly="readonly" ></td>
</tr>
<tr>
<td>Employee last name:</td>
<td><input type = "text" th:field="*{lastName}" ></td>
</tr>
<tr>
<td>Employee first name:</td>
<td><input type = "text" th:field="*{firstName}" ></td>
</tr>
<tr>
<td>Phone:</td>
<td style="display: none"><input type="text" id="destination" th:field="*{phone}"></td>
<td style="display: none"><input type="text" id="assignPhone" th:field="*{phone.assigned}"></td>
<td>
<select id="source" onchange="copyTextValue(), setBooleanForCurrentPhone()" th:field="${possiblePhones}" >
<option th:value="${employee.phone?.id}" th:text="${employee.phone != null ? employee.phone.brand +' '+ employee.phone.model : 'no phone'}">select phone</option>
<option th:each="possiblePhone : ${possiblePhones}" th:value="${possiblePhone.id}" th:text="${possiblePhone.brand +' '+ possiblePhone.model} "></option>
</select>
</td>
</tr>
<!--submit button-->
<tr>
<td colspan="2">
<button onclick="setBooleanForPhone()" type="submit">Save</button>
</td>
</tr>
</table>
I have found something on the internet but I am pretty sure that I am not doing it right:
function setBooleanForCurrentPhone() {
var n = 'false';
var http = new XMLHttpRequest();
http.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("assignPhone").innerHTML = this.responseText;
}
};
http.open("POST","employee/edit/{id}",true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(n);
}
You can use Ajax to achieve this. Ajax stands for Asynchronous JavaScript and XML. It will allow you to submit forms without refreshing the page. If you are using jQuery then you can do that using$ajax else if you are using JavaScript then it will be available using XMLhttprequest.

please enter a valid value the two nearest valid value is?

my assignment is to make weight calculator but due to limitations of university I am not able to use all tags so I write code it works fine but gives me a error of please enter a valid value the two nearest valid value are ***number*** and ***number***.
I think that is because of the number attribute in input tag but I can not able to find what's wrong and how to correct it.
There is one more error if I only calculate one conversion output flash on screen and vanished if I get output in all fields then answer is shown.
<html>
<head>
<title>Weight Convertor Calculator</title>
<script>
var z;
var x;
function converter() {
if (document.weight.kg.value >= 1) {
x = document.weight.kg.value;
document.getElementById("g").value = x * 1000;
document.getElementById("p").value = x * 2.2046;
document.getElementById("m").value = x * 1000000;
document.getElementById("ut").value = x * 0.0011023;
z = 35.274 * x;
document.getElementById("o").value = z;
} else {
window.alert("please enter any number greater than 0");
}
}
</script>
</head>
<body bgcolor="#b3f0ff">
<h1 align="center" style="color:#ff0066;"> Weight Calculator</h1>
<br>
<br>
<form name="weight" method="post">
<table align="center" style="color:#ff0066;">
<tr>
<td><b>Enter your weight in Kg:</b></td>
<td><input type="number" id="kg" name="kilogram" placeholder="enter_any_number"></td>
</tr>
<tr>
<td align="right"><input type="submit" value="Convert" onClick="converter(kg.value)"></td>
<td><input type="reset"></td>
</tr>
<tr>
<td align="right"><b>weight in Grams=</b></td>
<td><input type="number" id="g" name="gram"></td>
</tr>
<tr>
<td align="right"><b>weight in Pounds=</b></td>
<td><input type="text" id="p" name="pound"></td>
</tr>
<tr>
<td align="right"><b>weight in MilliGrams=</b></td>
<td><input type="number" id="m" name="milligram"></td>
</tr>
<tr>
<td align="right"><b>weight in US Ton=</b></td>
<td><input type="text" id="ut" name="uton"></td>
</tr>
<tr>
<td align="right"><b>weight in Ounces=</b></td>
<td><input type="number" id="o" name="ounce"></td>
</tr>
</table>
</form><br>
<p align="center" style="color:#ff0066;"><b>NOTE: Enter only numerical
value which is greater than 0</b></p>
</body>
</html>
Try adding the attribute step="any" to your input. That helped me.
No need to make input type 'text', just add one attribute step="0.01" with type="number" to accept decimal values.
In number inputs fragments are not allowed, so you need to use an text input.
Your form will be submitted: data gone
Here you can find a demo that works, based on your code.
Changing input typ from number to text will work.

I'm trying to create an html form to generate an url address based on input to a field

I am trying to create a small HTML document for my team to use to create fake devices for testing purposes in our program. We currently have a link to do this with but we have to manually change parts of it in the URL field before hitting enter to process it. I came up with the idea of creating this form so we can make sure that we are filling in all the elements of the URL correctly and then copy and paste the created URL into the browser. There are static parts of the address that we don't change and then there are values we update after the '=' sign. There are 4 different environments that we can use this in.
I admit it has been a while since I last worked in HTML so I've been trying to search forums and sites like W3School to find the segments of code that I think will serve the purpose I'm aiming for. The following code is where I have gotten so far but can't get it to work the way I've intended it to. If anyone can provide suggestions or feedback on what I missed or did wrong I'd appreciate it. Thank you!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Item birth generator</title>
<script>
function mySubmit() {
var addStart;
var addPart1 = "part1=";
var addPart2 = "&part2=";
var addPart3 = "&part3=";
var addPart4 = "&part4=";
var addPart5 = "&part5=";
var addPart6 = "&part6=";
var addPart7 = "&part7=";
var addPart8 = "&part8=";
var myChoice = "choice";
if (myChoice.value == "choice1")
{addStart="https://address1?";}
else if (myChoice.value == "choice2")
{addStart="https://address2?";}
else if (myChoice.value == "choice3")
{addStart="https://address3?";}
else (myChoice.value == "choice4")
{addStart="https://address4?";}
var address = addStart.concat(addPart1, "mInput1", addPart2, "mInput2", addPart3, "mInput3", addPart4, "mInput4", addPart5, "mInput5", addPart6, "mInput6", addPart7, "mInput7", addPart8, "mInput8");
document.getElementById("demo").innerHTML = address;
}
</script>
</head>
<body>
<font> <H3>Please fill in the appropriate fields and then click Generate to create a url for an item in the chosen environment.</H3></font>
<form target="_self" id="demo" name="item" method="post" onSubmit="return checkValue();">
<input type="radio" name="choice" id="ch1" value="choice1" checked> Choice 1 <input type="radio" name ="choice" id="ch2" value="choice2"> Choice 2 <input type="radio" name="choice" id="ch3" value="choice3"> Choice 3 <input type="radio" name ="choice" id="ch4" value="choice4"> Choice 4
<br><br>
<table>
<tbody>
<tr>
<td>Item Part 1</td>
<td><input type="text" name="mInput1" maxlength="13"></td>
</tr>
<tr>
<td>Item Part 2</td>
<td><input type="text" name="mInput2"></td>
</tr>
<tr>
<td>Item Part 3</td>
<td><input type="text" name="mInput3"></td>
</tr>
<tr>
<td>Item Part 4</td>
<td><input type="text" name="mInput4"></td>
<tr>
<td>Item Part 5</td>
<td><input type="text" name="mInput5"></td>
</tr>
<tr>
<td>Item Part 6</td>
<td><input type="text" name="mInput6"></td>
</tr>
<tr>
<td>Item Part 7</td>
<td><input type="text" name="mInput7"></td>
</tr>
<tr>
<td>Item Part 8</td>
<td><input type="text" name="mInput8"></td>
</tr>
<tr>
</tr>
<tr>
<td><input type="submit" value="Generate" onclick="mySubmit()"></td>
</tr>
</tbody>
</table>
<br>
<input type="text" size="250" name="address" value=''>
</form>
</body>
</html>
There is an error with this line:
var s.address = s.addStart.concat(addPart1, mInput1, addPart2, mInput2, addPart3, mInput3, addPart4, mInput4, addPart5, mInput5, addPart6, mInput6, addPart7, mInput7, addPart8, mInput8);
Verify what you are using is valid by testing the variables (output with a console.log or an alert) and check the command syntax. :)

HTML form with javascript conditional field and redirection

I am building a form allowing people to download a PDF upon submission.
Problem is that I am not able to include a conditional redirection on the form.
Would you mind having a look at the code?
JS
function OnSubmitForm() {
if (document.download.Resource[doc1].checked == true) {
document.download.action = "url1";
} else if (document.download.Resource[doc2].checked == true) {
document.download.action = "url2";
} else if (document.download.Resource[doc2].checked == true) {
document.download.action = "url3";
}
return true;
}
HTML
<p><strong>To download this article, please, complete the fields below</strong>
<p>Resource:</p>
<table width="100px" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>Doc1</td>
<td>
<input id="Resource" value="doc1" name="Resource" type="radio" validatethis="radio" checked="true">
</td>
</tr>
<tr>
<td>Doc2</td>
<td>
<input id="Resource" value="doc2" name="Resource" type="radio" validatethis="radio">
</td>
</tr>
<tr>
<td>Doc3</td>
<td>
<input id="Resource" value="doc3" name="Resource" type="radio" validatethis="radio">
</td>
</tr>
</tbody>
</table>
<input value="Submit" type="submit">
http://jsfiddle.net/0z8hu7tv/3/
Thanks a lot!

Java Script function not working?

I'm using this codes below but seems my setValue() method is not working. can someone point what is wrong with this codes?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script language="javascript">
function rand ( n )
{
document.getElementById("orderRefId").value = ( Math.floor ( Math.random ( ) * n + 1 ) );
}
function setValue(amount1)
{
myValue = amount1;
document.getElementById("amount").value = myValue;
}
</script>
</head>
<body onLoad="rand( 2000000 )">
<!--
Note: https://www.pesopay.com/b2c2/eng/payment/payForm.jsp for live payment URL
https://test.pesopay.com/b2cDemo/eng/payment/payForm.jsp for test payment URL
-->
<form method="POST" name="frmPayment" action="https://test.pesopay.com/b2cDemo/eng/payment/payForm.jsp">
<table>
<tbody>
<tr>
<td>Order Reference No. (your reference number for every transaction that has transpired):</td>
<td><input type="text" id="orderRefId" name="orderRef" value="Test-001"/></td>
</tr>
<tr>
<td>Amount:</td>
<td><input type="text" onLoad = "setValue()" name="amount" value=""/></td>
</tr>
<tr>
<td>Currency Code - "608" for Philippine Peso, "840" for US Dollar:</td>
<td><input type="text" name="currCode" value="608"/></td>
</tr>
<tr>
<td>Language:</td>
<td><input type="text" name="lang" value="E"/></td>
</tr>
<tr>
<td>Merchant ID (the merchant identification number that was issued to you - merchant IDs between test account and live account are not the same):</td>
<td><input type="text" name="merchantId" value="18056869"/></td>
</tr>
<tr>
<td>Redirect to a URL upon failed transaction:</td>
<td><input type="text" name="failUrl" value="http://www.yahoo.com?flag=failed"/></td>
</tr>
<tr>
<td>Redirect to a URL upon successful transaction:</td>
<td><input type="text" name="successUrl" value="http://www.google.com?flag=success"/></td>
</tr>
<tr>
<td>Redirect to a URL upon canceled transaction:</td>
<td><input type="text" name="cancelUrl" value="http://www.altavista.com?flag=cancel"/></td>
</tr>
<tr>
<td>Type of payment (normal sales or authorized i.e. hold payment):</td>
<td><input type="text" name="payType" value="N"/></td>
</tr>
<tr>
<td>Payment Method - Change to "ALL" for all the activated payment methods in the account, Change to "BancNet" for BancNet debit card payments only, Change to "GCASH" for GCash mobile payments only, Change to "CC" for credit card payments only:</td>
<td><input type="text" name="payMethod" value="ALL"/></td>
</tr>
<tr>
<td>Remark:</td>
<td><input type="text" name="remark" value="Asiapay Test"/></td>
</tr>
<!--<tr>
<td>Redirect:</td>
<td><input type="text" name="redirect" value="1"/></td>
</tr>-->
<tr>
<td></td>
</tr>
<input type="submit" value="Submit">
</tbody>
</table>
</form>
</body>
</html>
NOTE: the variable "amount1" is came from my android. and its not causing the problem because I'm using it in other codes.
I will be very thankful for any thoughts.
1.You don't have no DOMInputElement with id "amount". You need to change the html like this:
<input type="text" onLoad = "setValue()" name="amount" id="amount" value=""/>
Or the js like this:
function setValue(amount1)
{
myValue = amount1;
document.frmPayment.amount.value = myValue;
}
2.The second issue is that you cannot attach the onLoad event to input element. What you can do, is put the <script/> with setValue() call or change your <body> tag to:
<body onLoad="rand(200000);setValue();">
JavaScript is in the default settings disabled in the WebView. You need to activate it first.
YourWebView.getSettings().setJavaScriptEnabled(true);
You also need to correct your JavaScript. You call the function document.getElementById(...), but your input element has no Id but a name. So you need to call document.getElementsByName(...)[0].
function text() {
var dt = new Date();
dt.format("dd-mmm-yyyy");
var newdt = dt.getFullYear();
var tt = document.getElementById("ctl00_ContentPlaceHolder1_txtPolicyStartDate").value;
var dt2 = new Date.parseLocale(tt, 'dd-MMM-yyyy');
dt2.setFullYear(dt2.getFullYear() + 1);
dt2.setDate(dt2.getDate() - 1);
document.getElementById("ctl00_ContentPlaceHolder1_txtPolicyExpiryDate").value = dt2.format("dd-MMM-yyyy");
return dt2;
}

Categories