I was making a javascript function in which I need to confirm the input. I wrote the following code but its giving negative value i.e. "else" part even if i enter a valid value. Can some one please suggest a solution?
Html file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Javascript App</title>
<script type="text/javascript" src="app1.js">
</script>
</head>
<body><h1 id="heading1" style="text-align:center; height:auto; width:auto; font-family:'Arial Black', Gadget, sans-serif">Determinant of a nxn matrix</h1>
<p id="paragraph1" style="font-family:'Arial Black', Gadget, sans-serif"> This program allows you to compute the determinant of a nxn matrix</p>
<p>
Input the order of the matrix
<br />
<input type="text" maxlength="3" name="value" />
<input type="button" value="submit" onclick="verifyorder(value)" />
</p>
<p id="error"></p>
<p id="detspace"></p>
</body>
</html>
Javascript File:
function verifyorder(order){
;
if(order>0){
return true;
}
else{
alert("Sorry, you need to enter a positive integer value, try again");
document.getElementById('error').innerHTML="Sorry, you need to enter a positive integer value, try again";
}
}
Give the textbox an id of "txtValue" and change the input button declaration to the following:
<input type="button" value="submit" onclick="verifyorder(document.getElementById('txtValue').value)" />
Here is the JSfiddle Demo
I changed your HTML and give your input textfield an id of value. I removed the passed param for your verifyorder function, and instead grab the content of your textfield by using document.getElementById(); then i convert the str into value with +order so you can check if it's greater than zero:
<input type="text" maxlength="3" name="value" id='value' />
<input type="button" value="submit" onclick="verifyorder()" />
</p>
<p id="error"></p>
<p id="detspace"></p>
function verifyorder() {
var order = document.getElementById('value').value;
if (+order > 0) {
alert(+order);
return true;
}
else {
alert("Sorry, you need to enter a positive integer value, try again");
document.getElementById('error').innerHTML = "Sorry, you need to enter a positive integer value, try again";
}
}
Simply put id attribute in your input text field -
<input type="text" maxlength="3" name="value" id="value" />
Try: if(parseInt(order)>0){....
Related
I need some help in implementing a whitespace character check in a JSP input field.
Here's what my code and existing JSP code looks like:
function validation(){
var wsregex = /\s/g;
var input = document.getElementById("Division_").value;
var result;
if (result = input.match(wsregex)){
alert ("There is a whitespace in the Name field");
return false;
}
JSP Code:
<input type="hidden" name="Division_<%= divisionSeq %>" value="exist" />
<input class="button" type="submit" name="submit" value="Submit" onclick="return validate(this.form, <%=divisionSeq%>)"
I don't know what to change aside from what I have. The JSP code was built by a consultant who did not leave any documentation behind.
Thanks,
E.
I am not sure about the way you are calling that javascript function.
I am sharing what i did to make it work.
<html>
<head>
<script>
function validation(){
var wsregex = /\s/g;
var input = document.getElementById("input").value;
var result;
if (result = input.match(wsregex)){
alert ("There is a whitespace in the Name field");
return false;
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Enter a text : <input id="input" type="text" /><br>
<input type="submit"
value="Submit" onclick="validation()" />
</body>
</html>
Just enter any text and submit.It will check for whitespace and will give alert if found.
Javascript code
function validation(){
var wsregex = /\s/g;
var input = document.getElementById("Division_1").value;
var result;
if (result = input.match(wsregex)){
console.log ("There is a whitespace in the Name field");
return false;
}
JSP code:
input type="hidden" name="Division_<%= divisionSeq %>" value="exist" />
<input class="button" type="submit" name="submit" value="Submit" onclick="return validate()"
The <%=divisionSeq%> scriptlet is a counter so I tricked the js function to predict the initial value.
I have been reading several posts realted to this matter here on Stack Overflow and been reading the W3 Schools tutorials on Javascript and HTML forms.
I am creating an XHTML form with required fields for users to submit personal data (Name, Address, Phone). I want the onsubmit attribute to pass each input value as an argument to my external javascript function website_form_error().
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<script src="http://othermindparadigm.com/web_frm_err.js" type="text/javascript"></script>
</head>
<body>
<p class="mid" id="frm_responder"> </p>
<form action="/webformmailer.php" method="post" onsubmit="javascript:website_form_error(document.getElementById('Name').value,document.getElementById('Address').value,document.getElementById('Phone').value)">
<p>
* Name <input class="norm" type="text" name="Name" />
* Address <input class="norm" type="text" name="Address" />
* Phone <input class="norm" type="text" name="Phone" />
</p>
<input type="submit" />
</form>
</body>
</html>
The form has an external JavaScript file to be called when submitted. /web_frm_err.js
function website_form_error(Name,Address,Phone)
{
var = Name,Address,Phone,response ;
response = (Name,Address,Phone == undefined)
?
"Your specifications have been sent to Other Mind Paradigm"
:
"Form incomplete. You must fill in all required fields." ;
document.getElementById("frm_responder").innerHTML = response ;
}
I want the website_form_error() function to cancel the form submission and redirect back to the form and insert a message into <p id="frm_responder"> when the user has not filled in all of the required fields.
My website_form_error() function does not yet have a way to cancel the submission and the text to be inserted does not trigger. I'm sure there is something wrong with my Javascript. Any answers?
I think you should use simple button instead of submit button, on the simple button add a custom method on the event of onclick and use submit() in that custom method.
Well after days of frustration and reading, research, reading, reasearch I have got the form to cancel and error message to insert without event propagation. When the user completes the required fields the form is sent. One struggle I had was because I have a checkbox in the form. Checkboxes should be called for their checked state as a boolean for easier validation document.getElementById("Agree").checked, not by their values as this became a nightmare trying to solve.
My external Javascript /web_frm_err.js. This is as simplified as I could get. Each argument Name,Phone,Email,Theme,Images,Agree gets assigned a new variable name (n , p , e , t , i , a) in the function parameters.
function website_form_error(n , p , e , t , i , a)
{
var att = document.getElementById("err") ;
if ((n != "") && (p != "") && (e != "") && (t != "") && (i != "") && (a == true))
{
return true ;
}
else
{
att.innerHTML = "Form incomplete. You must complete all required (*) fields." ;
att.style.color = "Red" ;
return false ;
}
}
My XHTML form:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<script src="/web_frm_err.js" type="text/javascript"></script>
</head>
<body>
<form onsubmit="javascript:return website_form_error(document.getElementById('Name').value , document.getElementById('Phone').value , document.getElementById('Email').value , document.getElementById('Theme').value , document.getElementById('Images').value , document.getElementById('Agree').checked)" action="/webformmailer.php" method="post">
* Name <input type="text" id="Name" />
<br /> * Phone <input type="text" id="Phone" />
<br /> * Email <input type="text" id="Email" />
<br /> * Theme <input type="text" id="Theme" />
<br /> * Images <input type="text" id="Images" />
<br /> * Do you agree? <input type="checkbox" id="Agree" />
<p id="err"></p>
<br /><input type="submit" value="Send" />
</form>
</body>
</html>
An onsubmit handler attribute should return false to cancel the submission. Try using onsubmit="return website_form_error(...)" and returning a false from website_form_error to cancel the submission.
Your script should look like this:
function website_form_error(Name,Address,Phone)
{
var = Name,Address,Phone,response ;
response = (Name,Address,Phone == undefined)
document.getElementById("frm_responder").innerHTML = response ;
if(!response){
"Your specifications have been sent to Other Mind Paradigm";
return true;
}else{
"Form incomplete. You must fill in all required fields." ;
return false;
}
}
And your HTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<script src="http://othermindparadigm.com/web_frm_err.js" type="text/javascript"></script>
</head>
<body>
<p class="mid" id="frm_responder"> </p>
<form action="/webformmailer.php" method="post" onsubmit="javascript:website_form_error(document.getElementById('Name').value,document.getElementById('Address').value,document.getElementById('Phone').value)">
<p>
* Name <input class="norm" type="text" name="Name" />
* Address <input class="norm" type="text" name="Address" />
* Phone <input class="norm" type="text" name="Phone" />
</p>
<input type="submit" onclick="return website_form_error()"/>
</form>
</body>
</html>
I'm trying to build a proof of concept using an example I came up with to show how we can implement JavaScript within Sharepoint by building a calculator.
Everything seems to be fine but I'm giving myself a headache trying to figure out why everything is either undefinied or NaN.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<SCRIPT LANGUAGE="JavaScript">
function calc (form) {
var multipliers = [ 0.5, 0.25, 0.10, 0.05, 100, 50 ];
var bonus;
var imyindex = form.level.value-1;
if (form.level.value < 5)
{
bonus = (((form.salary.value * multipliers[imyindex]) * form.profit.value) * form.growth.value);
}
else bonus = multipliers[imyindex];
alert (multipliers[imyindex]);
alert (imyindex);
alert ("Your bonus is " + bonus);
}
</script>
</head>
<body>
<table width="161" border="-1">
<tr>
<td width="85%"><form id="form" name="form" method="get" action="">
<p>
<label for="level">Level: </label>
<select name="level" id="level">
<option value=”1”>A</option>
<option value=”2”>B</option>
<option value=”3”>C</option>
<option value=”4”>D</option>
<option value=”5”>E</option>
<option value=”6”>F</option>
</select>
</p>
<p>
<label for="salary">Salary: </label>
<input type="text" name="salary" id="salary" />
</p>
<p>
<label for="salary">Profit: </label>
<input name="profit" type="text" id="profit" value=".25" />
</p>
<p>
<label for="salary">Growth: </label>
<input name="growth" type="text" id="growth" value=".75" />
</p>
<p>
<center>
<INPUT TYPE="button" NAME="button" Value="Calculate" onClick="calc(this.form)"/>
</p>
</form></td>
</tr>
</table>
</body>
</html>
You have smart quotes around your <option> values. This is causing the value to be ”1” rather than just 1, and that's throwing your calculations way off.
You are using the wrong type of quotes. Perhaps you are using another text editor which introduced the curly quotes: ”.
This quotes make the the value selected to be ”1” rather than 1, therefore it is being mistakenly being marked as text, and therefore causing var imyindex = form.level.value-1; to equal NaN.
Replace the curly quotes to double " or single ' quotes, and your problem should be solved.
Here is the working code : You can't send form as a object to the function on click and the option shouldn't have string value or you could use parseInt to convert them to the integer
otherwise the working example is here live just use :)
http://jsfiddle.net/ALJ6W/
I'm the developer of software called Appizy that avoid headaches while creating calculators. Basically it transforms a OpenDocument spreadsheet into HTML+CSS+JS..
You just have to create your calculator on OpenOffice or LibreOffice. Then Appizy turns it instantly into a stand-alone web app.
I hope it can help you to solve your issue !
Best,
Nicolas
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script language="javascript">
//This is gobal array for currency and exchange rate which are used in this web page
var strCurrency=['Yen','US Dollar','Euro','Swiss Frank','Danish Korona'];
var dblExchangeRate=[128.7,1.59,1.15,2.06,9.69];
//this function will allow the user to see if their currency covert
function Currency()
{
//collect information from text boxes and combo box
var txtSterling=document.getElementById("txtSterling")
var sleCurrency=document.getElementById("cmbCurrency")
var txtCovert=document.getElementById("txtCovert")
var cmbCurrency=document.getElementById("cmbCurrency")
//this will make sure text box is empty from the start
txtCovert.value='';
//this will check to see when the user enter in numbers is vaild and there are no characters
if (isNaN(txtSterling.value))
{
txtSterling.value='';
alert('Please enter in numerical value only');
txtSterling.focus();
return;
//this will check the index of cmbCurrency and display the new currency coverstion in txtCovert. This is done by multiplying txtSterling by exchange rate for the new currency
var strSlectCurrency= cmbCurrency.selectedIndex;
var strCurrency= cmbCurrency.options[strSlectCurrency].text;
txtCovert.value= (txtSterling.value * dblExchangeRate[strSlectCurrency]).toFixed(2) + '' + strCurrency;
}
}
</script>
<body>
<h1 align="center">Money Currency Converter</h1>
<p align="left"> </p>
<p align="left">Please enter in the amount you wish to covert £
<input type="text" name="txtSterling" id="txtSterling"/>
</p>
<p align="left">Please select a currency
<select name="cmbCurrency" id="cmbCurrency" onChange="Currency()">
<option>Euro</option>
<option>US Dollar</option>
<option>Swiss Frank</option>
<option>Danish Korona</option>
<option>Yen</option>
</select>
</p>
<p align="left">
<input type="button" name="cmdCurrency" id="cmdCurrency" value="Convert" onCr65trfg5trrfrfd87lick="Currency()" />
</p>
<p align="left">
<input type="text" name="txtCovert" id="txtCovert" />
</p>
</body>
</html>
Why does nothing happen when I click "Convert", despite the fact that I have set an event handler on the button?
onCr65trfg5trrfrfd87lick should read onclick.
There are several things wrong with this code:
onCr65trfg5trrfrfd87lick should read onclick.
if (isNaN(txtSterling.value)) should be if (isNaN(parseInt(txtSterling.value,10))), since the former co-erces the empty string ("") to 0, which is not NaN. Your error handling block won't work without this change. Note also that this will not allow the user to write complex strings like "1,000". Improving this is left as an exercise to the reader.
You've put all your code into the empty string handling block. Even once this block is fixed, your code will be broken.
Your arrays strCurrency and dblExchangeRate do not match the order of currencies in the dropdown box, so the values are wrong.
The Danish currency is the Krone, not the Korona (which is a misspelt alcoholic beverage).
You've also misspelt "convert" in a few places.
Here's the fixed version (though IMO it still has style problems that are out of the scope of this question):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script language="javascript"><!--
//This is gobal array for currency and exchange rate which are used in this web page
var strCurrency=['Yen','US Dollar','Euro','Swiss Frank','Danish Krone'];
var dblExchangeRate=[128.7,1.59,1.15,2.06,9.69];
//this function will allow the user to see if their currency covert
function Currency() {
//collect information from text boxes and combo box
var txtSterling=document.getElementById("txtSterling")
var sleCurrency=document.getElementById("cmbCurrency")
var txtCovert=document.getElementById("txtCovert")
var cmbCurrency=document.getElementById("cmbCurrency")
//this will make sure text box is empty from the start
txtCovert.value='';
//this will check to see when the user enter in numbers is vaild and there are no characters
if (isNaN(parseInt(txtSterling.value, 10))) {
txtSterling.value='';
alert('Please enter in numerical value only');
txtSterling.focus();
return;
}
//this will check the index of cmbCurrency and display the new currency coverstion in txtCovert. This is done by multiplying txtSterling by exchange rate for the new currency
var strSlectCurrency= cmbCurrency.selectedIndex;
var strCurrency= cmbCurrency.options[strSlectCurrency].text;
txtCovert.value= (txtSterling.value * dblExchangeRate[strSlectCurrency]).toFixed(2) + ' ' + strCurrency;
}
//--></script>
<body>
<h1 align="center">Money Currency Converter</h1>
<p align="left"> </p>
<p align="left">Please enter in the amount you wish to covert £
<input type="text" name="txtSterling" id="txtSterling"/>
</p>
<p align="left">Please select a currency
<select name="cmbCurrency" id="cmbCurrency" onChange="Currency()">
<option>Yen</option>
<option>US Dollar</option>
<option>Euro</option>
<option>Swiss Frank</option>
<option>Danish Krone</option>
</select>
</p>
<p align="left">
<input type="button" name="cmdCurrency" id="cmdCurrency" value="Convert" onClick="Currency()" />
</p>
<p align="left">
<input type="text" name="txtCovert" id="txtCovert" />
</p>
</body>
</html>
See it working here.
Hope this helps.
Your if block is wrong. It should be
if (isNaN(txtSterling.value))
{
txtSterling.value='';
alert('Please enter in numerical value only');
txtSterling.focus();
return;
}
//this will check the index of cmbCurrency and display the new currency coverstion in txtCovert. This is done by multiplying txtSterling by exchange rate for the new currency
var strSlectCurrency= cmbCurrency.selectedIndex;
var strCurrency= cmbCurrency.options[strSlectCurrency].text;
txtCovert.value= (txtSterling.value * dblExchangeRate[strSlectCurrency]).toFixed(2) + '' + strCurrency;
Ok, I need help. This is my first question here.
Background:
I am working on a charity project, and my portion of the project is to build the Web-To-Case functionality with Salesforce.com. Salesforce.com, if you were unaware, gives its software away free to qualified non-profits. Anyway, the Web-To-Case feature in Salesforce.com generates an HTML form that, when submitted, will send the data back to Salesforce.com and create a ticket. The IDs for the form elements are strings of numbers and letters that would appear to correspond to the fields in Salesforce.com.
Goal:
I was trying to build in validation of the dates on a particular form because we found out that unless the dates were formatted just so (12/30/2009 12:00 PM), anything the user entered would not make it into Salesforce.com
Problem:
Found a script online (javascript) and modified it to suit my needs. Problem - it does not work. I get a little error in the corner of the browser but it doesn't stop the form from going through (it also doesn't validate) - "Expected ')'" on line 16.
I would love to attach the code here...I hope that's OK. Normally I would cut out only the relevant bits but I fear that people would then say "Hey this will never work - you don't have a closing HTML tag" or whatnot. I'm not sure if it will paste well - it came from a .htm file and the HTML may be interpreted by this forum and that would be...well...not ideal! Okay, I think I figured out how to escape it but there was so much to escape that I cut out most of the comments and most of the truly irrelevant things..
You can see how the form field ids are all funky - most of the examples I saw had straightforward form ids and names...so I wondered if Javascript just can't deal with strings starting with digits as id/names on fields.
I'm also wondering - because I can't verify it by testing since it's not working for other reasons - if my regular expression comes anything close to the date format I specified above. I had to make up my own regular expression since I didn't find anything out in the world like what I wanted.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Cambridge Cares About AIDS: Request an Asset</title>
<link type="text/css" rel="stylesheet" href="styles.css" />
<SCRIPT LANGUAGE="JavaScript"> // Original JavaScript code by Chirp Internet: www.chirp.com.au // Please acknowledge use of this code by including this header. //Code modified to validate a date/time field by Shannon Davis, Company Name Removed.
function checkDates(form)
{
checkDate(form.00N80000003LGJ5);
checkDate(form.00N80000003LGNt);
}
function checkDate(field)
{
var allowBlank = false;
var minYear = (new Date()).getFullYear();
var maxYear = 2100;
var errorMsg = "";
// regular expression to match required date format
re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})\s(\d{1,2}):(\d{2})+\s([ap]m)+$/;
if(field.value != '') {
if(regs = field.value.match(re)) {
if(regs[1] < 1 || regs[1] > 12) {
errorMsg = "Invalid value for day: " + regs[1];
} else if(regs[2] < 1 || regs[2] > 31) {
errorMsg = "Invalid value for month: " + regs[2];
} else if(regs[3] < minYear || regs[3] > maxYear) {
errorMsg = "Invalid value for year: " + regs[3] + " - must be between " + minYear + " and " + maxYear;
}
} else {
errorMsg = "Invalid date format: " + field.value;
}
} else if(!allowBlank) {
errorMsg = "Empty date not allowed!";
}
if(errorMsg != "") {
alert(errorMsg);
field.focus();
return false;
}
return true;
}
</SCRIPT>
<META HTTP-EQUIV="Content-type" CONTENT="text/html; charset=UTF-8">
</head>
<BODY>
<div id="container">
<div id="top_photo">
<img src="images/ccaa_banner.jpg" alt="banner" width="800" height="181" />
</div>
<div id="left_colum" style="width: 200; height: 256"><a href="index.html">
<img src="images/cca_logo.gif" alt="logo" border="0" width="178" height="84" /></a>
<p class="address">Cambridge Cares About AIDS<br />17 Sellers Street<br /> Cambridge, MA 02139<br />617.661.3040</p>
<br />
</div>
<div id="right_colum">
<div id="content">
<form id="form" name="form" action="https://www.salesforce.com/servlet/servlet.WebToCase?encoding=UTF-8" method="POST">
<input type=hidden name="orgid" value="00D80000000M3if">
<input type=hidden name="retURL" value="http://wilmwebtest/CCAA/thank_you.htm">
<table border=0>
<tr><TD><label for="email">CCA Email:*</label></TD><td><input id="email" maxlength="80" name="email" size="40" type="text" /><br> </td></tr>
<tr>
<td><label for="subject">Subject:</label></td><td><input id="subject" maxlength="80" name="subject" size="40" type="text" /><br></td>
</tr>
<tr><td>
<label for="description">Description*</label></td>
<td>
<textarea name="description" rows="4" cols="25"></textarea><br></td>
</tr><tr>
<input type="hidden" name="recordType" id="recordType" value="0012800000006ZWz">
<tr> <td colspan="2">
<p>Date Format: mm/dd/yyyy hh:mm am/pm<br>example: "08/30/2009 12:00 am"</td></tr>
<tr><td>When Needed (Start):*</td>
<td><input id="00N80000003LGJ5" name="00N80000003LGJ5" size="40" type="text" /></span><br></td></tr>
<tr>
<td>
When Needed (End):<span class="dateInput">*</td>
<TD>
<input id="00N80000003LGNt" name="00N80000003LGNt" size="40" type="text" /></span><br></td>
</tr>
</table>
<input type="hidden" id="external" name="external" value="1" /><br>
<input type="submit" name="submit" value="Submit Asset Request" onClick="checkDates (this.form);" >
</form>
</div>
</div>
<div id="clearit">
</div>
</div>
</body>
</html>
Your checkDate function is correct. The problem is in your checkDates function. Javascript doesn't like variables that begin with numbers. Change it to:
function checkDates(form)
{
checkDate(form.elements['00N80000003LGJ5']);
checkDate(form.elements['00N80000003LGNt']);
}
and it should work as intended.
Also, in order for an invalid date to cancel the form from being submitted, you must change your submit button's onClick attribute to:
onclick="return checkDates( this.form )"
Otherwise, the form will be submitted no matter what.
On a side note, the error message you mention sounds like a classic 'WTF?' Internet Explorer error message. Consider upgrading to the latest version of IE (IE8), which has much better error messages than the previous versions, or using Firefox. Firefox's Error Console is second to none when it comes to tracking down Javascript (and CSS) errors.