I'm trying to test a HTML web form, but I'm experiencing some problems.
The form opens a secondary HTML file (showing a success message) if all data is entered correctly. If data is not entered, or if data is entered incorrectly, the field name should turn red and a message is displayed directing the user to re-enter the information.
I opened the file directly from Finder (I'm on Mac) to Google Chrome, where it displays fully. However, regardless of what I put (or don't put) in the input fields, the code directs me to the success message.
The code is as follows:
<head>
<title>Form</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.Entry.name.value=="") {
msg+="You must enter your name \n";
document.Entry.name.focus();
document.getElementById(‘name’).style.color="red";
result = false;
}
if (document.Entry.age.value=="") {
msg+="You must enter your age \n";
document.Entry.age.focus();
document.getElementById(‘age’).style.color="red";
result = false;
}
if (document.Entry.number.value=="") {
msg+="You must enter your number \n";
document.Entry.number.focus();
document.getElementById(‘number’).style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Form</h1>
<form name="Entry" 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="age">Age</td>
<td><input type="text" name="age" /></td>
</tr>
<tr>
<td id=”number”>Number</td>
<td><input type="text" name="number"/></td>
</tr>
<tr>
<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>
I have looked over the code and I am sure it is correct, so why doesn't the HTML work as intended?
Your code contains errors including:
Wrong " ' " chars
Wrong ' " ' chars
Using the reserved word 'number'
The following is the fixed working (at least in Firefox) code:
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
<script type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.Entry.name.value=="") {
msg+="You must enter your name \n";
document.Entry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.Entry.age.value=="") {
msg+="You must enter your age \n";
document.Entry.age.focus();
document.getElementById('age').style.color="red";
result = false;
}
if (document.Entry.mumber.value=="") {
msg+="You must enter your number \n";
document.Entry.mumber.focus();
document.getElementById('number').style.color="red";
result = false;
}
if(msg == ""){
return result;
}
else
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Form</h1>
<form name="Entry" id="Entry" method="post" action="success.html" onsubmit="return validateForm()">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="age">Age</td>
<td><input type="text" name="age" /></td>
</tr>
<tr>
<td id="number">Number</td>
<td><input type="text" name="mumber"/></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
It will be wise to initiate the 'result' variable as 'false'. This way you need to update it only once - when 'msg' is empty.
It seems that you should choose some other editor/IDE. Also, try to debug your JS scripts - you have debuggers for all modern browsers. I personally use Firebug addon for Firefox. Many people use Chrome developer tools.
Also, you may find this simple reference handy:
http://www.w3schools.com/js/js_form_validation.asp
Your form action is success.html so your form is submitting to this page regardless of your javascript.
The Javascript function is firing on click but its a submit button so the submit is still firing. The page its submitted to is success.html so this is continually being called regardless because the form is continuously being submitted.
The issue comes from how you are accessing the form inputs. Type this into a console, or at the start of your script block:
console.log(document.Entry);
It'll print out undefined. Your code is throwing an error, failing and never returning a false value to prevent the form from submitting.
I suggest taking a look at this question to see various ways of accessing form inputs using vanilla javascript.
I've rewrite your code. Now it's working. You can check working example JSFiddle - http://jsfiddle.net/uj5xcp26/ or copy&paste example below:
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Form</h1>
<form name="Entry" 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">Age</td>
<td><input type="text" name="age" id="age" /></td>
</tr>
<tr>
<td id=”number”>Number</td>
<td><input type="text" name="number" id="number"/></td>
</tr>
<tr>
<td><button onclick="validateForm();" id="submit_btn" type="button" name="Submit" value="Submit">Submit</button></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
<script type="text/javascript">
//Assuring page is loaded
document.onload = function(){
validateForm();
};
var validateForm = function() {
var result = true;
var msg="";
var name,age,number;
name = document.getElementsByName("name")[0];
age = document.getElementsByName("age")[0];
number = document.getElementsByName("number")[0];
//Conditionals
if (name.value =="") {
msg+="You must enter your name \n";
name.focus();
name.style.color="red";
result = false;
}
if (age.value=="") {
msg+="You must enter your age \n";
age.focus();
age.style.color="red";
result = false;
}
if (number.value=="") {
msg+="You must enter your number \n";
number.focus();
number.style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg);
return result;
}
};
</script>
</body>
</html>
Firstly try putting your script after your form in the body.
Secondly I agree with above your form action will fire regardless. Can you not handle message with innerHTML.
Related
I am trying to get an alert whenever a user clicks on the username or password input field and exits it without entering. However, I am able to get this to work after using "onblur" instead of "onfocus" (Thanks to Gurvinder's answer below). Now, the alert seems to work for both the fields when I click outside of the form using "onfocus". However, when I use tab key to get to password field from username field to password field, the "passwordCheck" function keeps running. Please help.
<!DOCTYPE html>
<html>
<head>
<title>Javascript exercises</title>
<meta charset="UTF-8">
</head>
<body>
<form name="myForm" >
<table>
<tr>
<td>Username:</td>
<td><input name="username" id="userName" type="text" onfocus="userNameCheck();"></input></td>
</tr>
<tr>
<td>Password:</td>
<td><input name="password" id ="password" type="password" onfocus="passwordCheck();"></input></td>
</tr>
<tr>
<td></td>
<td><input type="Button" value="Submit"></input></td>
</tr>
</table>
</form>
<script>
//User name field validator - Alert a message for empty input fields
var userNameCheck = function() {
if(document.myForm.username.value == ""){
alert("User Name cannot be blank");
}
else{
return false;
}
}
//password field validator - Alert a message for empty input fields
var passwordCheck = function() {
if(document.myForm.password.value == ""){
alert("Password cannot be blank");
}
else{
return false;
}
}
</script>
</body>
</html>
I want the username input to show an alert if the user clicks on it
and tabs to the next field without entering any data.
If you are using focus event to check for the input validity, then unless value is pre-populated, alert will keep coming.
Use blur event, onblur instead of onfocus.
<td><input name="username" id="userName" type="text" onblur="userNameCheck();"></input></td>
Demo
<body>
<form name="myForm">
<table>
<tr>
<td>Username:</td>
<td><input name="username" id="userName" type="text" onblur="userNameCheck();"></input>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input name="password" id="password" type="password"></input>
</td>
</tr>
<tr>
<td></td>
<td><input type="Button" value="Submit"></input>
</td>
</tr>
</table>
</form>
<script>
//User name field validator - Alert a message for empty input fields
var userNameCheck = function() {
if (document.myForm.username.length >= 1) {
//Nothing happens
} else {
alert("User Name cannot be blank");
return false;
}
}
</script>
</body>
Why not create your own 'alert' div for more control (and better user experience).
$("input").focus(function(){
var x = document.forms["myForm"]["password"].value;
if (x == "") {
/*alert("Password cannot be blank");*/
$('.alert').show();
return false;
}
});
And to specify tab key scenario, try:
function checkTabPress(key_val) {
if (event.keyCode == 9) {
$('.alert').hide();
}
}
I'm using a barcode-scanner to add data to some html fields. What I want to do is the following
focus on first field
scan and enter data into the first field
switch the focus to the second field
scan and enter data into the second field
submit form
I tried two approaches:
Catching the carriage return sent by the hand scanner
Catching every keystroke in the textfield
Posted is the latter one.
It works sofar, but only if I leave my debug alerts in the code...
If I remove them, the form is submitted...
Any idea why?
<html>
<head>
<head>
<title>Webinterface</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</head>
<script type="text/javascript">
function processForm(e) {
if (e.preventDefault) e.preventDefault();
return false;
}
function checkFieldC(text)
{
if(text.length==6){
alert("C1");
if(document.comform.Destination.value.length>0){
alert("C2a");
document.forms["comform"].submit();
return true;
}else{
alert("C2b");
document.comform.Destination.focus();
return false;
}
}
return false;
}
function checkFieldD(text)
{
if(text.length==9){
if(document.comform.Container.value.length>0){
alert("D2a");
document.forms["comform"].submit();
return true;
}else{
alert("D2b");
document.comform.Container.focus();
return false;
}
}
return false;
}
</script>
<form method="POST" name="comform" action="DoSomething.php">
<br>
<table width="90%" border="0">
<tr>
<td valign="top" width="150">Container (6 digits)</td>
<td><input name="comvalue[]" type="text" id="Container" size="10" maxlength="6" onkeyup="checkFieldC(this.value)" ></td>
</tr>
<br>
<tr>
<td valign="top" width="150">Destination:</td>
<td><input name="comvalue[]" type="text" id="Destination" size="10" onkeyup="checkFieldD(this.value)"></td>
</tr>
<tr>
<td>Confirm</td>
<td><button name="s2" onClick="submit()" class="cssButton1">Confirm</button></td>
</tr>
</table>
</font>
</form>
</body>
</html>
Ok, I found a solution deep in this post how to prevent buttons from submitting forms
After defining the button type
<button type="button">Button</button>
it works perfectly. Thanks for your support :)
Hi I am trying to do simple validation on a form. The form validates on chrome but not on Mozilla Firefox and Internet Explorer.
Comment Form HTML
<form method="post">
<table class="table-form">
<tr>
<td><label for="comment_name">Name<span class="orange">*</span></label></td>
<td><input type="text" name="name" placeholder="Your full name" id="comment_name"><span class="orange"></span></td>
</tr>
<tr>
<td><label for="comment_email">Email (Optional)</label></td>
<td><input type="email" name="email" placeholder="neo#example.com" id="comment_email"/><span class="orange"></span></td>
</tr>
<tr>
<td><label for="comment_country">Country (Optional)</label></td>
<td><input type="text" name="country" placeholder="eg. India" id="comment_country"/><span class="orange"></span></td>
</tr>
<tr>
<td><b>Comment <span class="orange">*</span></b></td>
<td><textarea textarea id="comment_text_area" name="comment" placeholder="Write your comment here."></textarea><span class="orange"></span></td>
</tr>
</table>
<input type="button" id="submit-comment" value="Sumbit"/>
</form>
Script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit-comment').click(function(){
$('#comment_name').next().html('');
$('#comment_email').next().html('');
$('#comment_text_area').next().html('');
var comment_name=$('#comment_name').val();
var comment_email=$('#comment_email').val();
var comment_country=$('#comment_country').val();
var comment_text_area=$('#comment_text_area').val();
var characterReg = /^\s*[a-zA-Z,\s]+\s*$/;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!characterReg.test(comment_name)||name=='') {
$('#comment_name').next().html('Invalid Name');
} else if(!emailReg.test(comment_email)) {
$('#comment_email').next().html('Invalid Email Format.');
} else if(comment_text_area=='') {
$('#comment_text_area').next().html('Please enter a comment.');
} else {
alert('Validated!');
}
});
});
</script>
I see the validation error message 'Invalid Name' on Internet Explorer and Mozilla Firefox. The code shows the Alert 'Validated!' on Goggle Chrome.
Someone please tell me where I am going wrong. I am using the latest versions of all browsers.
You might have to try removing this condition (name=='') from
if(!characterReg.test(comment_name)||name=='') {
$('#comment_name').next().html('Invalid Name');
}
to something like this
if(!characterReg.test(comment_name)) {
$('#comment_name').next().html('Invalid Name');
}
variable name is returned as empty in static web page, where as in codepen(CodePen)/jsfiddle(result) we get some value
I have a computing assignment to do.
I've done most I'm just stuck on this task:
"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."
I have done the Radio Buttons I just don't know how to do the second part with the Alertbox and function.
So far my code looks like this:
<html>
<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 \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.examno.value == "") {
msg += "You must enter your Examination Number \n";
document.ExamEntry.examno.focus();
document.getElementById('examinationno').style.color = "red";
result = false;
}
if (msg=="") {
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<! Main HTML content begins >
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr></tr>
<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="examinationno">Examination Number</td>
<td><input type="text" name="examno" maxlength="4" /></td>
</tr>
<tr>
<td><input type="radio" name="Level" value="GCSE">GCSE</td>
</tr>
<tr>
<td><input type="radio" name="Level" value="AS">AS</td>
</tr>
<tr>
<td><input type="radio" name="Level" value="A2">A2</td>
</tr>
<tr>
<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>
All you have to do is add the value of the radio button to the message like this:
msg += "Level of Entry: "+document.ExamEntry.Level.value;
Here is a fiddle demo you can try
EDIT #1: Though it has been said to use an alert box, that wouldn't actually allow the user to confirm or reject, for that, you could use confirm instead:
if (confirm("Click OK to confirm your Level of Entry or Cancel if you would like to correct it"))
return true;
else
return false;
In my example, I added it only in case the rest of the form validation was successful: http://jsfiddle.net/Qd8sk/2/
EDIT #2: Following our conversation, I updated the jsfiddle you created. It is much more simple than what you provided.
Here is yours: http://jsfiddle.net/Kjxmn/
Here is mine: http://jsfiddle.net/Kjxmn/2/
Several things I changed:
-1. Added return in front of the function name in onchange - looks like otherwise it would still submit even on return false.
-2. Corrected the form name that you called radioform this time, not Exam Entry.
-3. Got rid of the slightly cumbersome check of the selected value using if (document.radioform.level.value == '') instead.
-4. Added the confirm check.
EDIT #3: Looks like firefox doesn't like the usage of document.ExamEntry.Level.value for radio buttons, so instead I created a quick workaround that would loop through the elements of document.ExamEntry.Level and find the one that is 'selected' ('checked' actually - even though it's a radio button, the js code is still called 'checked').
Have a look at the updated fiddle: http://jsfiddle.net/Qd8sk/3/
function confirm () {
var alerttxt = "Are you sure you want to choose",
value = document.ExamEntry.name.value;
alerttxt += value;
alert(alerttxt);
}
The value variable holds the value the user chose in the radio button, you just want to append that to a message you make up and display that whole txt in an alert
I am using a microcontroller and I'm communicating with it via a html page.
The pages are stored as some constant in the microcontroller and are sent to PC for display purposes.
I want to attach my variable data at the end of html page that is sent into the PC to display them in the boxes that are in the middle of the page.
Before that I was forced to find the exact position of variable in the html in the box .
Is there any way to show the data that is attached at the end of the html in the middle boxes of the page?
<!DOCTYPE html>
<html>
<head>
<title>SAAT Co</title>
<h1><center><font color="red"> SAAT Co </font></center></h1>\r\n<h1><fontcolor="blue"> Ethernet Display T24M08 </font></h1>\r\n
<script>
<--
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
-->
</script>
</head>
<body>
<form name="myForm" action="http://192.168.1.250" onsubmit="return validateForm()" method="post">
<table>
<tr>
<td>Firmware Version :</td>
<td><input type="text" name="dev-info" value=" " ></td>
</tr>
<tr>
<td>MAC Adress :</td>
<td><input type="text" name="mac-addr"></td>
</tr>
<tr>
<td>IP Adress :</td>
<td><input type="text" name="ip-addr"></td>
</tr>
</table>
<input type="submit" value="Apply/Reboot">
</form>
</body>
</html>
If I understand you correctly, you can accomplish what you're trying to do by assigning your values to their appropriate textboxes. The example below does this by giving your textbox an ID and then using javascript to insert your value into that textbox.
<td>MAC Adress :</td>
<td><input type="text" id='MacAddy' name="mac-addr"></td>
...
</form>
</body>
</html>
<script>
document.getElementById('MacAddy').value = "your_value_here";
</script>
The javascript can be appended to the document in the fashion you described in your post.