Form does not take in new values - javascript

HTML
<form action="./Login.php" method="post" onsubmit="return checkInput();">
<table width="300" border="1">
<tbody>
<tr>
<th> UserName: </th>
<td><input class="box" type="text" value="" name="uname" id="uname"></td>
</tr>
<tr>
<th>Password: </td>
<td><input class="box" type="password" value="" name="pword" id="uname"></td>
</tr>
</tbody>
</table>
<input type="hidden" id="infoDis" value=""/>
<input type="submit" value="Log-in" name="login">
<input type="submit" value="Reset" name="reset">
</form>
JS
function checkInput()
{
var v1 = document.getElementsByName("uname");
var v2 = document.getElementsByName("pword");
var uname = v1[0].getAttribute("value");
var pword = v2[0].getAttribute("value");
if (uname == "" || pword == "")
{
if(uname == "" && pword != "")
{
alert("Error: Username is Empty. Please Enter Username.");
}
else if(pword == "" && uname != "")
{
alert("Error: Password is Empty. Please Enter Password");
}
else
{
alert("Error: Username And Password is Empty. Please Enter Username and Password");
}
location.reload();
return false;
}
return true;
}
Hi guys. I am new to html/js. I having a small issue where when i enter new values into the textbox. It does not being captured by the javascript. In turn, after a few debugging i found that the javascript is always taking the value in the html tag. Hence, even if value is entered in the first try or in the retry phase, the javascript takes the value in the html "" tag. Please Help Thx.

Because you are reading values using getAttribute
"getAttribute() returns the value of a specified attribute on the element"
Use Element.value to read the value property of the InputElement
Whenever value of the Element is changed, property of the Element is being updated not the attribute
function checkInput() {
var v1 = document.getElementsByName("uname");
var v2 = document.getElementsByName("pword");
var uname = v1[0].value;
var pword = v2[0].value;
if (uname == "" || pword == "") {
if (uname == "" && pword != "") {
alert("Error: Username is Empty. Please Enter Username.");
} else if (pword == "" && uname != "") {
alert("Error: Password is Empty. Please Enter Password");
} else {
alert("Error: Username And Password is Empty. Please Enter Username and Password");
}
location.reload();
return false;
}
return true;
}
<form action="./Login.php" method="post" onsubmit="return checkInput();">
<table width="300" border="1">
<tbody>
<tr>
<th>UserName:</th>
<td>
<input class="box" type="text" value="" name="uname" id="uname">
</td>
</tr>
<tr>
<th>Password:</th>
<td>
<input class="box" type="password" value="" name="pword" id="uname">
</td>
</tr>
</tbody>
</table>
<input type="hidden" id="infoDis" value="" />
<input type="submit" value="Log-in" name="login">
<input type="submit" value="Reset" name="reset">
</form>
Note: Refer .prop() vs .attr() question to gain more understanding!

jQuery to the resuce!
Some people love it, and others hate it. I wouldn't rely on it as your sole frontend library, but if you need to do simple DOM manipulation/interaction, then jQuery is usually a good solution. Grabbing the data stored from a form element is simple in jQuery.
$(document).ready(function() {
$('.button').on('click', function() {
var text = $('#some_element).val();
$('#another_element').append(text);
});
});
The API docs have easy examples. http://api.jquery.com/val/

Simply change to this:
var uname = v1[0].value;
var pword = v2[0].value;
.value returns the value of the input element

You can also get value using jquery very easily:
var uname = $("input[name=uname]").val();
var pword = $("input[name=pword]").val();

Related

Uncaught ReferenceError: validateForm is not defined at HTMLInputElement.onclick

why do I have this problem? I'm trying to get an output to the user name in the site. but it keeps giving me this problem!
I ant it to write me that the user name is not correct when im starting with a number or it is blanked at all- it gives me nothing.
please help me I am sitting on this above an hour:((
Snippet
function validateForm() {
var res = true;
res = userNameVal() && res;
return res;
}
function userNameVal() {
var userName = document.getElementById("username").value;
var msgBox = document.getElementById("userNameCheck");
if (userName.length == 0) {
msgBox.innerHTML = "You must enter user name";
msgBox.style.color = "red"
return false;
}
if (!isLetter(userName[0])) {
msgBox.innerHTML = "User name must start with a letter ";
msgBox.style.color = "red";
return false;
}
msgBox.innerHTML = "";
return true;
}
<form id="form1" method="post" onsubmit="return validateForm()">
<table class="table3">
<tr>
<td>
<label for="username">User Name:</label>
</td>
<td>
<input type="text"
name="username"
id="username"
onchange="userNameVal()" />
</td>
<td>
<div id="userNameCheck"></div>
</td>
</tr>
<tr>
<td><input type="button"
value="submit"
onclick="return validateForm()"/>
<input type="reset" value="reset" />
</td>
<td></td>
<td></td>
</tr>
</table>
</form>

Facebook App form won't submit

Ok so I have this email sign up form that I use on my website. I got the script directly from the email management system as they are the ones that process the form.
I'm using it on my website and it works perfectly but when I try and run the same script in a Facebook App it fails to submit. Actually that's not strictly true as it does pop up with the 'You need to agree to the terms...' if left unchecked but it doesn't get any further than that.
I've tested it in a browser and it works so I know there's nothing wrong with the code, I'm just baffled as to why it won't function in Facebook.
Here is the script exactly how it appears on the page.
<form action="http://www.elabs12.com/functions/mailing_list.html" method="post" name="UPTml807" onSubmit="return (!(UPTvalidateform(document.UPTml807)));">
<input type="hidden" name="submitaction" value="3">
<input type="hidden" name="mlid" value="807">
<input type="hidden" name="siteid" value="2012000210">
<input type="hidden" name="tagtype" value="q2">
<input type="hidden" name="demographics" value="1,2,-1,40836,37592">
<input type="hidden" name="redirection" value="http://www.MYWEBISTE.com/WebContent/Promotions/PromotionsNewEmailThanks.htm">
<input type="hidden" name="uredirection" value="http://">
<input type="hidden" name="welcome" value="">
<input type="hidden" name="double_optin" value="">
<input type="hidden" name="append" value="on">
<input type="hidden" name="update" value="on">
<input type="hidden" name="activity" value="submit">
<div class="textfield">
<table border="0" cellspacing="0" cellpadding="5" width="100%">
<tr>
<td><span class="formText">Your First Name*</span><br/><input type="text" name="val_1" class="firstName" size="10" value="" /></td>
<td><span class="formText">Your Last Name*</span><br/><input type="text" name="val_2" class="lastName" size="10" value="" /></td>
</tr>
<tr>
<td colspan="2"><span class="formText">Your Email*</span><br/><input type='text' name='email' class="email" value='' style='display:block'/></td>
</tr>
<tr>
<td colspan="2"><span class="formText">Your Mobile Number</span><br/>
<input type='text' name='val_3' class="mobile" value='' style='display:block'/></td>
</tr>
<tr>
<td><div style="text-align:left; margin:0 0 20px 0px"><input type="checkbox" id="val_37592" name="val_37592" style="width:20px; height:10px;">
<span class="formText">I accept your Privacy Policy (below)*</span><br/><br/><span style="font-size:12px !important;" class="formText">*Required field</span></div></td>
<td align="right"><input type="submit" name="submit" value="Submit" class="submitBTN" /></td>
</tr>
</table>
</div>
<script language="Javascript">
function emailCheck (emailStr) {
var emailPat=/^(.+)#(.+)$/;
var specialChars="\\(\\)<>#,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
var atom=validChars + '+';
var word="(" + atom + "|" + quotedUser + ")";
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
var matchArray=emailStr.match(emailPat);
if (matchArray==null) {
alert("Email address seems incorrect (check # and .'s)");
return false;
}
var user=matchArray[1];
var domain=matchArray[2];
if (user.match(userPat)==null) {
alert("The username doesn't seem to be valid.");
return false;
}
var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {
for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
alert("Destination IP address is invalid!");
return false;
}
}
return true;
}
var domainArray=domain.match(domainPat);
if (domainArray==null) {
alert("The domain name doesn't seem to be valid.");
return false;
}
var atomPat=new RegExp(atom,"g");
var domArr=domain.match(atomPat);
var len=domArr.length;
if ((domArr[domArr.length-1] != "info") &&
(domArr[domArr.length-1] != "name") &&
(domArr[domArr.length-1] != "arpa") &&
(domArr[domArr.length-1] != "coop") &&
(domArr[domArr.length-1] != "aero")) {
if (domArr[domArr.length-1].length<2 ||
domArr[domArr.length-1].length>3) {
alert("The address must end in a three-letter domain, or two letter country.");
return false;
}
}
if (len<2) {
var errStr="This address is missing a hostname!";
alert(errStr);
return false;
}
return true;
}
function UPTvalidateform(thisform)
{
if (document.getElementById("val_37592").checked==false){alert("Please let us know you have read and agree to the Terms and Conditions of this email alert sign up"); return(true);}
if (thisform.val_1.value==""){
alert("Please enter a value for First Name");
return(true);}if (thisform.val_2.value==""){
alert("Please enter a value for Last Name");
return(true);}
if (emailCheck(thisform.email.value))
{
if ((document.getElementById('unsubscribe')
&& document.getElementById('unsubscribe').checked) && (document.getElementById('showpopup') && document.getElementById('showpopup').value == "on")) {
alert('Thank you, now you are unsubscribed!');
}
else if(( (document.getElementById('unsubscribe')
&& !document.getElementById('unsubscribe').checked) || (!document.getElementById('unsubscribe')) ) && (document.getElementById('showpopup') && document.getElementById('showpopup').value == "on")){
alert('Thank you for signing up!');
}
return false;
}
else
{
return true;
}
}
</script>
</form>
I've tried removing the JS to see if Facebook was blocking it and I just get the same result. I've even tried submitting to a different URL but no luck.
Is there something I've missed/am I being blind? Or maybe it's a deeper issue...
Any help is much appreciated.
Thank you.
The url you submit to must be registred in the app details. Try changing the app domains in facebook developers.
Further more if you're browsing facebook in secure mode (default setting) it will block all content from non-ssl urls. so http://www.elabs12.com/functions/mailing_list.html would have to be https://www.elabs12.com/functions/mailing_list.html

Validation not working on Javascript

I have worked out how to get the alert box up but it seems to skip my other validation which is checking the other feilds, ect, any ideas as too why it is skiiping it? it would really help!
I am fairly new to Javascript and HTML so could you explain it, thank you
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
window.validateForm=function() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
//result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value == "") {
msg += "You must enter the exam Number \n";
document.ExamEntry.subject.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value.length != 4) {
msg += "You must enter at least Four Numbers in the Exam Number \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var Number = document.ExamEntry.Exam_Number.value
if (isNaN(document.ExamEntry.Exam_Number.value)) {
msg += "You must enter at least four numeric characters in the Exam Number feild \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var checked = null;
var inputs = document.getElementsByName('Exam_Type');
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (checked == null) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} {
alert(msg)
return false;
}
}
</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="Exam_Number">Exam Number</td>
<td><input type="text" name="Exam_Number"<font size="1">(Maximum characters: 4)</font> </td>
</tr>
<tr>
<table><form action="">
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
and here is a jsfiddle
Change:
var inputs = document.getElementsByName('Exam_Type');
to
var inputs = document.getElementsByName('examtype');
It seems you picked the wrong name for the radio elements.
Your for loop was checking the radio buttons incorrectly.
Code:
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
}
}
Please find the working fiddle here http://jsfiddle.net/sDLV4/2/
I changed code here please check...
Please find the working fiddle here
http ://jsfiddle.net/sDLV4/3/
Using HTML5 constraint validation, much of your code can be dropped, see my revision below. In addition to the wrong radio button group name pointed out by Juergen Riemer, your code has the following issues:
Better use the HTML5 DOCTYPE declaration, see below
Instead of <script language="javascript" type="text/javascript"> just use <script>. The script element does not have a language attribute, and the type attribute has the value "text/javascript" by default.
Do not define your validation function on the window object, but rather as global function (as below), or preferably as a member of a namespace object.
Instead of setting the form's name attribute to "ExamEntry", rather set its id attribute and reference the form of a variable like var examForm = document.forms["ExamEntry"];
Your HTML code is not well-formed, because in your form's table, on line 79, you start another table element with another form element, both of which do not have an end tag.
Also, it's preferable to us CSS for the form layout, instead of a table.
In my revision below I'm using a Pure CSS stylesheet for styling forms, and corresponding class values in certain elements.
For more about constraint validation in general and the HTML5 constraint validation features, see this tutorial.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<title>Exam entry</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/combo?pure/0.3.0/base-min.css&pure/0.3.0/forms-min.css" />
<script>
function validateForm() {
var result = true;
var msg = "";
var checked = null;
var examForm = document.forms['ExamEntry'];
var inputs = examForm.examtype;
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (!checked) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} else {
alert(msg)
return false;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form id="ExamEntry" class="pure-form pure-form-aligned" method="post" action="success.html">
<div class="pure-control-group">
<label for="exNo">Exam Number:</label>
<input id="exNo" name="Exam_Number" required="required" pattern="\d{4}" title="You must enter a 4-digit exam number" />
</div>
<div class="pure-control-group">
<label>Exam type:</label>
<label class="pure-radio"><input type="radio" name="examtype" value="GCSE" /> GCSE</label>
<label class="pure-radio"><input type="radio" name="examtype" value="A2" /> A2</label>
<label class="pure-radio"><input type="radio" name="examtype" value="AS" /> AS</label>
</div>
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" onclick="return validateForm();">Submit</button>
<button type="reset" class="pure-button">Reset</button>
</div>
</form>
</body>
</html>

JavaScript Button Error

The issue I have with my JavaScript is that when I select the "Send" button for a blank form, it tells me which fields to complete (which I want). After selecting "OK", it asks me to "Please enter a valid email address." in another window.
Can anyone help me with the functions and logic to eliminate this second window if one selects "Send" without filling out the form? Do I need to create a new function for "Entering a valid email address"?
Here's the code:
javascript
function checkforblank() {
var errormessage = "";
if (document.getElementById('fname').value =="") {
errormessage += "enter your first name \n";
}
if (document.getElementById('lname').value =="") {
errormessage += "enter your last name \n";
}
if (document.getElementById('email').value =="") {
errormessage += "enter your email \n";
}
if (document.getElementById('confirmEmail').value =="") {
errormessage += "confirm your email \n";
}
if (errormessage != "") {
alert(errormessage);
return false;
}
};
function verifyEmail() {
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.myForm.email.value.search(emailRegEx) == -1) {
alert("Please enter a valid email address.");
}
else if (document.myForm.email.value != document.myForm.confirmEmail.value) {
alert("Email addresses do not match. Please retype them to make sure they are the same.");
}
else {
alert("Thank you for your interest!");
status = true;
}
return status;
}
function confirmEmailAddresses() {
checkforblank();
verifyEmail();
}
html
<div id="content">
<form name="myForm" action="#" method="get" enctype="application/x-www-form-urlencoded" onsubmit="">
<table width="377" height="96">
<tr>
<td style="text-align: right">First Name:</td>
<td><label for="FirstName"></label>
<input type="text" name="fname" id="fname"></td>
</tr>
<tr>
<td style="text-align: right">Last Name:</td>
<td><label for="LastName"></label>
<input type="text" name="lname" id="lname"></td>
</tr>
<tr>
<td style="text-align: right">E-mail:</td>
<td><input type="email" name="email" id="email"></td>
</tr>
<tr>
<td style="text-align: right">Confirm E-mail:</td>
<td><input type="email" name="confirmEmail" id="confirmEmail"></td>
</tr>
</table>
<input type="submit" value="Send" onClick="confirmEmailAddresses()"><input type="reset" value="Reset Form">
</form>
</div>
I'm fairly new to JavaScript, so please make this as easy as possible! :) Thank you.
replace
function confirmEmailAddresses(){
checkforblank();
verifyEmail();
}
with
function confirmEmailAddresses(){
if ( checkforblank() ) {
verifyEmail();
}
}
and add else return true; like so
if (errormessage != "") {
alert(errormessage);
return false;
} else return true;
so if (in the checkforblank() function) errormessage is not (!=) empty ("") then checkforblank() tells the script (returns) true and if (in confirmEmailAddresses() now) and only if checkforblank() is truthy (true is kinda pretty truthy) then verifyEmail() is run, the end (;). :p
Is this what you want?
function confirmEmailAddresses() {
if(checkforblank() && verifyEmail())
return true;
else return false;
}
ok i think what your asking for is this (jquery)
$(":submit").click( function(event) {
if(!checkforblank() || !verifyEmail()) {
event.preventDefault();
}
});
if you do this make sure to include after then button in the html. or enclose in a $(document).ready

Validating multiple fields in a form

I was doing the testing for the first time. I read the this code and made one of my own from it. The thing is that its not giving any error even if the fields are left empty.
Here is my fiddle.
Please help out. Thanks.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
{function validateForm()
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["password"].value;
{
if (y==null || y=="")
alert("Password name must be filled out");
return false;
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name*: <input type="text" name="name"> <br>
Password*: <input type="password" name="password"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
​
Fixed code: jsfiddle
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validateForm() {
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["password"].value;
if (y==null || y=="") {
alert("Password name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name*: <input type="text" name="name"> <br>
Password*: <input type="password" name="password"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
<html>
Be careful of where you place your braces. Additionally, it is advantageous to use the console on your browser to identify some errors and fixed them.
​
Your brace should be after function validateForm() and after the if, and at the end of the function. Overall, the braces are screwed in this example.
Lay your code out so the opening and closing braces match up and make sense to you.
You missed some braces {} and one was in the wrong spot.
Hope this works:
function validateForm() {
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["password"].value;
{
if (y==null || y=="")
alert("Password name must be filled out");
return false;
}
}
You misplaced the braces { } for validation of password. Place them after if clause.
I found it on Internet after a long time searching.. But it works just perfect..
The html code
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm"
onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
the javascript
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
and the function for email validation
<script type="text/javascript">
<!--
function validateEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>
you can check it online here

Categories