I'm trying to create a HTML Page with multiple forms, and I would like
to show the values from the form on the same page (wiping the original HTML), but after using the button, nothing shows up (the page like reloaded)
Here's the code for HTML :
function Results() {
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var gender = document.getElementById('gender').value;
var date = document.getElementById('birthday').value;
if (document.getElementById('genderM').checked) {
gender = document.getElementById('genderM').value;
} else if (document.getElementById('genderF').checked) {
gender = document.getElementById('genderF').value;
}
document.writeIn("<h3>Thank You! Here's Your Precious Data! </h3>"); document.writeIn("<p> Your Name Is : </p>" + fname + lname); document.writeIn("<p> Gender : " + gender); document.writeIn("<p> Birthday : " + birthday);
document.getElementById('forms').innerHTML = forms;
}
<!DOCTYPE HTML>
<html>
<head>
<title> The Page Number 2 </title>
<link rel="stylesheet" type="text/css" href="page2.css">
</head>
<body>
<h1> Please fill in the form for exciting contents! </h1>
<hr size="5px" color="black">
<div id="forms" class="forms">
<form onsubmit="Results()" method="post">
<div class="textFirst">
First Name
</div>
<input id="fname" type="text" name="fname"> <br>
<br>
<div class="textLast">
Last Name <br>
</div>
<input id="lname" type="text" name="lname"> <br>
<br>
<div class="textGender">
Gender <br>
<input id="genderM" type="radio" name="gender" value="male"> Male <br>
<input id="genderF" type="radio" name="gender" value="female"> Female <br>
</div>
<br>
<div class="textBirth">
Birthday <br>
</div>
<input id="birthday" type="date" name="birthday"> <br>
<input id="submit" class="buttonagain" type="submit" value="Submit!" />
</form>
</div>
</body>
</html>
Any ideas what should I do?
Edit : I'm not able to use php or server for this
Your code is riddled with syntax errors: missing parentheses, missing + operators, etc.
document.writeIn (with an uppercase I) is not a function; document.writeln (with a lowercase L) is.
<script> tags aren't self-closing, i.e. you have to write <script src="scriptPage2.js"></script>
document.getElementById('gender') returns null, because there is no element with id="gender".
You're trying to write birthday but you never declared that variable.
I have no idea what you're trying to accomplish with document.getElementById('forms').innerHTML = forms;
In general, you should make use of the browser's built-in debugger to catch all these errors. If you're using Chrome or Firefox, press Ctrl+Shift+I (in IE or Edge, press F12) and open the "Console" tab; you will see all the errors there as the JS parser encounters them.
Once that's all fixed, remove the submit event handler from <form>, and change your submit button like this:
<input id="submit" class="buttonagain" type="button" onclick="Results()" value="Submit!" />
Note the change of type from submit to button. This will prevent the page from reloading, which is the expected behavior when submitting a form.
You don't need the return and ; when calling a js function in html
<form onsubmit="Results()" method="post">
This is your answer.
function Results() {
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var gender;
var date = document.getElementById('birthday').value;
if (document.getElementById('genderM').checked) {
gender = "Male";
} else {
gender = "Female"
}
document.writeln("<h3>Thank You! Here's Your Precious Data! </h3>");
document.writeln("<p> Your Name Is : </p>" + fname + " " + lname);
document.writeln("<p> Gender : " + gender);
document.writeln("<p> Birthday : " + date);
document.getElementById('forms').style.display = "none";
}
<!DOCTYPE HTML>
<html>
<head>
<title> The Page Number 2 </title>
<link rel="stylesheet" type="text/css" href="page2.css">
</head>
<body>
<h1> Please fill in the form for exciting contents! </h1>
<hr size="5px" color="black">
<div id="forms" class="forms">
<form onsubmit="Results();" method="post">
<div class="textFirst">
First Name
</div>
<input id="fname" type="text" name="fname" required> <br>
<br>
<div class="textLast">
Last Name <br>
</div>
<input id="lname" type="text" name="lname"required> <br>
<br>
<div class="textGender">
Gender <br>
<input id="genderM" type="radio" name="gender" value="male" required> Male <br>
<input id="genderF" type="radio" name="gender" value="female"> Female <br>
</div>
<br>
<div class="textBirth">
Birthday <br>
</div>
<input id="birthday" type="date" name="birthday"required> <br>
</div>
<input id="submit" class="buttonagain" type="submit" value="Submit!" />
</div>
</form>
</body>
</html>
Related
I want to user to press submit button so that their name and age is displayed in the input box with name="output"?
I have 3 input boxes, one asking for name and the other for age while the other one provides output. I am trying to use the function output() to display the last input box.
I am confused about where I am going wrong, do I need a .value?
<!doctype html>
<html>
<head>
<style>
.formdiv{
align: center;
}
</style>
</head>
<body>
<script language="javascript" type="text/javascript">
function output(){
var name = getElementByName('firstName');
var Age= getElementByName('age');
var out = document.write(name+Age);
document.getElementByName('output') = out;
}
</script>
<h1><strong><em><center>Payment Details</center></em></strong> </h1>
<div class="formdiv">
<fieldset><center>
<legend> Enter the following Info:</legend>
<br />
<label> Name </label>
<input type="text" name="firstName" placeholder="John" required="required"></input>
<br/>
<br/>
<label>Age </label>
<input type="number" name="age" maxlength="2" required="required"></input>
</fieldset>
</center>
</div>
<div>
<center>
<button onClick="output()">Submit</button><br/>
<label for="output">Output</label>
<br/>
<input type="textbox" name="output"></input>
</center>
</div>
</body>
</html>
Here's a working version of your code.
There's no method getElementByName (but getElementsByName) - you should use document.getElementById() (Read about it here)
You should use the value of the input element.
<!doctype html>
<html>
<head>
<style>
.formdiv{
align: center;
}
</style>
</head>
<body>
<script language="javascript" type="text/javascript">
function output(){
var name = document.getElementById('firstName').value;
var Age= document.getElementById('age').value;
document.getElementById('output').value = name+Age;
}
</script>
<h1><strong><em><center>Payment Details</center></em></strong> </h1>
<div class="formdiv">
<fieldset><center>
<legend> Enter the following Info:</legend>
<br />
<label> Name </label>
<input type="text" id="firstName" placeholder="John" required="required"></input>
<br/>
<br/>
<label>Age </label>
<input type="number" id="age" maxlength="2" required="required"></input>
</fieldset>
</center>
</div>
<div>
<center>
<button onClick="output()">Submit</button><br/>
<label for="output">Output</label>
<br/>
<input type="textbox" id="output"></input>
</center>
</div>
</body>
</html>
getElementsByName (note: Elements, not Element) returns a list of Elements, in this case your <input>s. So first of all, you need to select the first (in your case your only one) using getElementsByName(...)[0]. Then you get one Element.
However you do not want to output the entire element (which is an Object, not a String, and converted to a string it likely won't be what you expect), so you need to select the value property of that Element. So yes, you need to add .value, just as you assumed:
function output(){
var name = getElementsByName('firstName')[0].value;
var Age= getElementsByName('age')[0].value;
Then, document.write writes the argument to a new document directly, which results in an emtpy page with nothing else on it but that string. This isn't what you want, so you don't need that. ALl you do want is to assign a new variable called out with that string:
var out = name+Age;
Then to assigning the new value to the output field - you don't want to replace the Element by a string (that wouldn't even work), but it's value, so you need the .value again:
document.getElementsByName('output')[0].value = out;
}
That should do the trick.
(In addition to that, you might want to use name + " " + Age instead of simply name+Age, as otherwise you end up with "John Doe23" instead of "John Doe 23" which you likely want)
There are a few things wrong with your code:
there is no such thing as getElementByName - it is getElementById
changing to the above, you need to add ids to your input elements
you need to use the value of the returned object from getElementById
The above will get your code working, but also, the center tag is obsolete and you shouldn't use it
Inputs are self closing tags so you don't need </input>
<!doctype html>
<html>
<head>
<style>
.formdiv {
align: center;
}
</style>
</head>
<body>
<script language="javascript" type="text/javascript">
function output() {
var name = document.getElementById('firstName').value;
var Age = document.getElementById('age').value;
var out = name + Age;
document.getElementById('output').value = out;
}
</script>
<h1><strong><em><center>Payment Details</center></em></strong> </h1>
<div class="formdiv">
<fieldset>
<center>
<legend>Enter the following Info:</legend>
<br />
<label>Name</label>
<input type="text" name="firstName" id="firstName" placeholder="John" required="required"></input>
<br/>
<br/>
<label>Age</label>
<input type="number" name="age" id="age" maxlength="2" required="required"></input>
</fieldset>
</center>
</div>
<div>
<center>
<button onClick="output()">Submit</button>
<br/>
<label for="output">Output</label>
<br/>
<input type="textbox" name="output" id="output"></input>
</center>
</div>
</body>
</html>
Using HTML and JavaScript only, I am trying to get the first name, surname details and then a choice of favourite colour from three radio buttons. I can get the first name and surname to work, but cannot do the radio buttons?
HTML file:
<html>
<title>Task 3</title>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form name="formDetails">
First Name:<input type="text" id="firstName"><br>
Last Name:<input type="text" id="lastName"><br>
<p>Favourite Colour:</p>
<input type="radio" name="colour" value="Red">Red<br>
<input type="radio" name="colour" value="Blue">Blue<br>
<input type="radio" name="colour" value="Green">Green<br>
<input type="button" onclick="display()" value="Submit">
</form>
</body>
JavaScript file:
function display(){
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
alert(firstName + " " + lastName);
}
I have no idea how to implement the radio buttons? I have seen some people using jQuery, but I want to stick to just JavaScript here as I am fairly new.
Thanks.
Js:
var colour=document.querySelector('input[name="colour"]:checked').value;
alert(colour);
Steps:
Add a class to all your input tags named check_in.
Use javascript to find all tags with this class
Iterate through each tag to determine which of them is checked. If a tag is checked add it to the variable named results.
Finally get First name and Last name from input box and add these values to your variable named results
function display() {
results = {}
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var all_input = document.getElementsByClassName('check_in');
for (var i = 0; i < all_input.length; ++i) {
if (all_input[i].checked == true) {
results['option'] = all_input[i].value;
}
}
results['firstname'] = firstName;
results['lastname'] = lastName;
console.log(results);
alert('firstname:' + results['firstname'] + ' lastname: ' + results['lastname'] + ' option: ' + results['option']);
}
margin:50px auto auto;
<html>
<title>Task 3</title>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form name="formDetails">
First Name:
<input type="text" id="firstName">
<br>Last Name:
<input type="text" id="lastName">
<br>
<p>Favourite Colour:</p>
<input type="radio" name="colour" value="Red" class="check_in">Red
<br>
<input type="radio" name="colour" value="Blue" class="check_in">Blue
<br>
<input type="radio" name="colour" value="Green" class="check_in">Green
<br>
<input type="button" onclick="display()" value="Submit">
</form>
</body>
Thanks to having to work so much, I am completely confused on JavaScript. I have tried so many things and have not gotten my form to validate even once. I have to use plain JavaScript to:
**Validate the email - the email must have # and the domain should be yahoo.com
Phone No.: Must contain exactly 10 digits
Age: Must be a positive number less than 120
The validation should happen when the user submits the form. In case any of the above validation fails, the corresponding fields should be highlighted in red
If the validation is successful, the page should redirect to http://yahoo.com**
I'm not looking for someone to necessarily give me the exact answer, but push me in the right direction, because I do have a basic understanding of JS.
<!DOCTYPE HTML>
<div id="form">
<form name="myForm" action="http://fsu.edu" onsubmit="return validateForm()" method="post">
<head>
<link rel="stylesheet" HREF="C:\Users\Neshia\Desktop\CGS3066\Form Validation Style Sheet.css" TYPE="text/css">
<script>
function ValidatemyForm()
{
var email = document.myForm.email;
var phone = document.myForm.phonenumber;
var age = document.myForm.age;
}
{
age = age.replace(/[^0-9]/g, '');
if(age.length != 10)
{
alert("not 10 digits");
}
else {
alert("yep, its 10 digits");
}
}
</script>
</head>
<div id="header">
<hr id="HR1">
<h1> Web Programming: Assignment 3 </h1>
<p> Form Validation with Javascript </p>
<hr id="HR2">
</div>
<div id="input">
First name: <br>
<input type="text" name="firstname">
<br>
Last name: <br>
<input type="text" name="lastname">
<br>
FSU Email: <br>
<input type= "text" name="email">
<br>
Phone No.: <br>
<input type="numbers" name="phonenumber">
<br>
Age: <br>
<input type="numbers" name="age">
</div>
<hr id="HR3">
<br>
<div id="Sex">
Sex: <br>
<input type="radio" name="sex" value="male"> Male
<br>
<input type="radio" name="sex" value="female"> Female
<br>
<input type="radio" name="sex" value="other"> Other
</div>
<hr id="HR32">
<div id="languages">
Programming languages you want to learn: <br>
<input type="checkbox" name="python" value="python"> Python
<br>
<input type="checkbox" name="java" value="java"> Javascript
<br>
<input type="checkbox" name="C++" value="C++"> C++
<br>
<input type="checkbox" name="lisp" valie="lisp"> Lisp
</div>
<hr id="HR32">
<div id="submit">
<input type="Submit" value="Submit">
</div>
<hr id="HR12">
</form>
</div>
Aneshia,
You have a few problems. First the function listed in the "onsubmit" attribute of your form does not match your javascript function. Also there are some problems with your {} braces. After you get that fixed be sure to call .value after your form elements to get the value of the input ie. (document.myForm.email.value).
Here is the code with some fixes:
<form name="myForm" onsubmit="return validateForm()" method="post">
<head>
<link rel="stylesheet" HREF="C:\Users\Neshia\Desktop\CGS3066\Form Validation Style Sheet.css" TYPE="text/css">
<script>
function validateForm() {
var email = document.myForm.email.value;
var phone = document.myForm.phonenumber.value;
var age = document.myForm.age.value;
console.log(age)
var okToSubmit = true;
age = age.replace(/[^0-9]/g, '');
if (age.length != 10) {
alert("not 10 digits");
okToSubmit = false;
} else {
alert("yep, its 10 digits");
}
if (age > 120 || age < 0) {
alert("Must be a positive number less than 120");
okToSubmit = false;
}
return okToSubmit;
}
Another thing that may help is to bring up the javascript console in your browser and run your function manually in the console by typeing 'validateForm();'
You may be intrigued to note that html5 now validates some of these forms so you do not need to use Javascript.
See HTML Form Validation
You asked about email, age and phone.
Consider the following examples::
<form>
<input type="email" name="email" pattern=".*#yahoo\.com"> <br>
<input type="number" min="18" max="120" name="age"> <br>
<input type="tel" name="phonenumber"> <br>
<input type='submit'>
</form>
If you want the fields to be required you could use
<form>
<input type="email" name="email" pattern=".*#yahoo\.com" required> <br>
<input type="number" min="18" max="120" name="age" required> <br>
<input type="tel" name="phonenumber" required> <br>
<input type='submit'>
</form>
See http://diveintohtml5.info/forms.html
In your comments a few days later, you mentioned needing to do this in Javascript. I think the best way is still using HTML5 and a clever way to do this if you have to use javascript might be to set the input attributes through javascript. Something like this could get you started on the logic.
While I generally do not like getting this specific in the code, I commented things so you can get a general feel for how you can work with data in javascript.
function validate(event){
// First we stop the form from even submitting until we run the code below
event.stopPropagation();
// Here we are going to place a reference to the objects we want to validate in an array
var references = ['email','age','phonenumber'];
// Now we are going to grab our list of inputs from the page
var inputs = document.getElementsByTagName('input');
// We run through a for loop to look for specific elements
for(i = 0; i < inputs.length; i++){
/*
This line simply asks, is the 'name' of this element inside our references array.
This works by using the indexOf function which is built into Javascript.
indexOf simply provides the index where it finds the phrase you are looking for.
In this example, we are using it to see if an index exists by checking it against negative 1
*/
if(references.indexOf(inputs[i].getAttribute('name')) > -1){
// A switch block lets you present a different outcome based on the criteria being looked for
switch(inputs[i].getAttribute('name')){
// In this case we see if we get an email named element
case 'email':
// We set the attributes to match our requirements for this email element and so on through this switch block for age and phonennumber
inputs[i].setAttribute('type','email');
inputs[i].setAttribute('pattern','.*#yahoo\.com');
break;
case 'age':
inputs[i].setAttribute('type','number');
inputs[i].setAttribute('min',18);
inputs[i].setAttribute('max',120);
break;
case 'phonenumber':
inputs[i].setAttribute('type','tel');
break;
}
// When we are all done, we set the elements to be required
inputs[i].setAttribute('required',true);
}
}
// Now we submit the form
event.submit();
}
<form>
<input type="text" name="email"> <br>
<input type="text" name="age"> <br>
<input type="text" name="phonenumber"> <br>
<input type='submit' onclick='validate(event)'>
</form>
<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='Javascript:checkEmail();'/>
<script language="javascript">
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>
What I want the program to do is make a form and have 2 radio buttons and 1 text.
Then I want it to collapse the text and radio value together into one and take me to that page:
If I input text with like "facebook" and the radiobutton value is .com I want it to take facebook + .com and send me to that page.
<!doctype html>
<html>
<head>
<title>A Basic Form</title>
<style type="text/css">
</style>
</head>
<body onunload="Bye()">
<form>
<fieldset>
<legend>Redirection: </legend>
<div>
<label>Where do you want to go?</label>
<input type="text" id="input" name="input" size="7">
<input type="submit" id="submit" name="submit" value="Submit" onclick="go()">
</div>
<div>
<input type="radio" id="no" name="end" value=".no">
<label for=".no">.no</label>
<br />
<input type="radio" id="com" name="end" value=".com">
<label for=".com">.com</label>
</div>
</fieldset>
</form>
<script type="text/javascript">
function go() {
var end = "";
if (document.getElementById("no").checked) {
end = document.getElementById("no").value;
} else {
end = document.getElementById("com").value;
}
var input = document.getElementById("input").value;
var together = input + end;
window.location.replace("http://www." + together);
}
</script>
</body>
</html>
Change type="submit" to type="button".
Change this line:
<input type="submit" id="submit" name="submit" value="Submit" onclick="go()">
to:
<input type="button" id="submit" name="submit" value="Submit" onclick="go()">
In this case you don't need to submit a form. You are just trying to redirect the url. You didn't specify where to submit the form so it is submitting to itself that is your problem.
Alternatively, return false from the onclick handler to prevent the form submit.
Try this code:
<html>
<head>
</head>
<body>
<form>
<fieldset>
<legend>Redirection: </legend>
<div>
<label>Where do you want to go?</label>
<input type="text" id="input" name="input" size="7">
<input type="submit" id="submit" name="submit" value="Submit" onclick="return go()">
</div>
<div>
<input type="radio" id="no" name="end" value=".no">
<label for=".no">.no</label>
<br />
<input type="radio" id="com" name="end" value=".com">
<label for=".com">.com</label>
</div>
</fieldset>
</form>
<script type="text/javascript">
function go() {
var end = "";
if (document.getElementById("no").checked) {
end = document.getElementById("no").value;
} else {
end = document.getElementById("com").value;
}
var input = document.getElementById("input").value;
var together = input + end;
window.location.replace("http://www." + together);
return false;
}
</script>
</body>
</html>
brso05's analysis seems to be spot on... But I can't really explain it. It seems that Chrome is delaying the side effects of the location.href.replace (which should be navigating away from the page) until after the form submit... I have a feeling you have hit a browser bug here. I can't imagine this is spec-compliant.
Please correct the below code it is not working as expected i.e, i need a error message to be shown just beside the textfield in the form when user enters an invalid name
<html>
<head>
<script type="text/javascript">
function validate() {
if(myform.fname.value.length==0)
{
document.getElementById("fname").innerHTML="this is invalid name ";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
Try this code
<html>
<head>
<script type="text/javascript">
function validate() {
if(myform.fname.value.length==0)
{
document.getElementById('errfn').innerHTML="this is invalid name";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input><div id="errfn"> </div>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
I m agree with #ReNjITh.R answer but If you want to display error message just beside textbox. Just like below
<html>
<head>
<script type="text/javascript">
function validate()
{
if(myform.fname.value.length==0)
{
document.getElementById('errfn').innerHTML="this is invalid name";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()" /><span id="errfn"></span>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"/><br>
<input type=button value=check />
</form>
</body>
web masters or web programmers, please insert
<!DOCTYPE html>
at the start of your page. Second you should enclose your attributes with quotes like
type="text" id="fname"
input element should not contain end element, just close it like:
/>
input element dont have innerHTML, it has value sor your javascript line should be:
document.getElementById("fname").value = "this is invalid name";
Please write in organized way and make sure it is convenient to standards.
you can try it like this
<html>
<head>
<script type="text/javascript">
function validate()
{
var fnameval=document.getElementById("fname").value;
var fnamelen=Number(fnameval.length);
if(fnamelen==0)
{
document.getElementById("fname_msg").innerHTML="this is invalid name ";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input>
<span id=fname_msg></span>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
You can also try this
<tr>
<th>Name :</th>
<td><input type="text" name="name" id="name" placeholder="Enter Your Name"><div id="name_error"></div></td>
</tr>
function register_validate()
{
var name = document.getElementById('name').value;
submit = true;
if(name == '')
{
document.getElementById('name_error').innerHTML = "Name Is Required";
return false;
}
return submit;
}
document.getElementById('name').onkeyup = removewarning;
function removewarning()
{
document.getElementById(this.id +'_error').innerHTML = "";
}
First you are trying to write to the innerHTML of the input field. This will not work. You need to have a div or span to write to. Try something like:
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input>
<div id="fname_error"></div>
Then change your validate function to read
if(myform.fname.value.length==0)
{
document.getElementById("fname_error").innerHTML="this is invalid name ";
}
Second, I'm always hesitant about using onBlur for this kind of thing. It is possible to submit a form without exiting the field (e.g. return key) in which case your validation code will not be executed. I prefer to run the validation from the button that submits the form and then call the submit() from within the function only if the document has passed validation.
Try like this:
function validate(el, status){
var targetVal = document.getElementById(el).value;
var statusEl = document.getElementById(status);
if(targetVal.length > 0){
statusEl.innerHTML = '';
}
else{
statusEL.innerHTML = "Invalid Name";
}
}
Now HTML:
<!doctype html>
<html lang='en'>
<head>
<title>Derp...</title>
</head>
<body>
<form name="myform">
First_Name
<input type="text" id="fname" name="fname" onblur="validate('fname','fnameStatus')">
<br />
<span id="fnameStatus"></span>
<br />
Last_Name
<input type="text" id="lname" name="lname" onblur="validate('lname','lnameStatus')">
<br />
<span id="lnameStatus"></span>
<br />
<input type=button value=check>
</form>
</body>
</html>
You should use .value and not .innerHTML as it is a input type form element
<html>
<head>
<script type="text/javascript">
function validate() {
if(myform.fname.value.length==0)
{
document.getElementById("fname").value="this is invalid name ";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
Setting innerHtml of input value wont do anything good here, try with other element like span, or just display previously made and hidden error message.
You can set value of name field tho.
<head>
<script type="text/javascript">
function validate() {
if (myform.fname.value.length == 0) {
document.getElementById("fname").value = "this is invalid name ";
document.getElementById("errorMessage").style.display = "block";
}
}
</script>
</head>
<body>
<form name="myform">First_Name
<input type="text" id="fname" name="fname" onblur="validate()"></input> <span id="errorMessage" style="display:none;">name field must not be empty</span>
<br>
<br>Last_Name
<input type="text" id="lname" name="lname" onblur="validate()"></input>
<br>
<input type="button" value="check" />
</form>
</body>
FIDDLE
try this
<html>
<head>
<script type="text/javascript">
function validate() {
if(myform.fname.value.length==0)
{
document.getElementById("error").innerHTML="this is invalid name ";
document.myform.fname.value="";
document.myform.fname.focus();
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type="text" id="fname" name="fname" onblur="validate()"> </input>
<span style="color:red;" id="error" > </span>
<br> <br>
Last_Name
<input type="text" id="lname" name="lname" onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
You should place your script code after your HTML code and within your body tags. That way it doesn't run before the html code.