This is a simple code and I don't know where I went wrong.. Name validation works if no name is entered, but it doesn't show the result when a valid name is entered.
Here's my code:
I'm just new in html and javascript, hoping i'd get help from here. Thank you
function checkname(form) {
var eobj = document.getElementById('MITname');
var jname = form.Name.value;
var error = false;
eobj.innerHTML = '';
if (jname == '') {
error = "Name is required!";
var error2 = error.fontcolor("red");
}
if (error) {
if (hasFocus == false) {
form.Name.focus();
hasFocus = true;
}
eobj.innerHTML = error2;
return false;
}
return true;
}
function showinput() {
document.getElementById('namedisplay').innerHTML = document.getElementById('MITname').value;
}
function validate() {
hasFocus = false;
var form = document.forms['form'];
var ary = [checkname];
var rtn = true;
var z0 = 0;
for (var z0 = 0; z0 < ary.length; z0++) {
if (!ary[z0](form)) {
rtn = false;
}
}
return rtn;
}
<form action="" name="form" onsubmit="return validate()">
<tr>
<td align="right">Name:<font color="red">*</font>
</td>
<td>
<input type="text" name="Name" /> <span id="MITname"> </span>
</td>
</tr>
<br/>
<input type="submit" value="Submit" onclick="showinput()" />
<br/>
<label>Your input:</label>
<p><span id="namedisplay"></span>
</p>
</form>
Few issues here. (Also, welcome to Web Development!)
First, you never actually create the variable hasFocus. So you're never actually checking if it's true/false or not.
Second, where you create error2 means that it will only be accessible within the if() block it was created in. So, in the following if(error) block when you try to access it, it will return undefined.
Third, when you create error you are setting the value to false, which indicates a Boolean type, but then later setting its value to a String, which is definitely not a Boolean.
Fourth, the line var ary = [checkname]; is confusing to me. I get that you're trying to convert the name (from the input?) to an array, but that is not the way to do it. You can access each character of the name with string.charAt(index), so creating an array isn't really necessary.
Fifth, your validate() function as a whole is very confusing. I haven't a clue what you're trying to do. It looks like your teaching source may have mislead you, or you weren't paying attention that closely.
I could go on, however those (among other) issues are really making it difficult to find exactly what is going wrong, without digging too much into it. I don't want to write this for you, and so my suggestion would be to start again, and maybe checkout some more tutorials, perhaps from a different source. (Different youtube channel, etc.)
My problem is the validation. If I enter a blank name, an error message should appear next to the Name's text box indicating to enter a valid name.
<!DOCTYPE html>
<html>
<head>
<title>JAVASCRIPT FORM VALIDATION</title>
<script type="text/JavaScript">
function showMessage()
{
var Name = document.getElementById("Name").value;
displayname.innerHTML= Name;
var Email = document.getElementById("Email").value;
displayemail.innerHTML= Email;
var Website = document.getElementById("Website").value;
displaywebsite.innerHTML= Website;
var Comment = document.getElementById("Comment").value;
displaycomment.innerHTML= Comment;
var nameerror='';
var emailerror='';
var websiteerror='';
var commenterror='';
if (displayname.innerHTML=='')
{
nameerror = 'Please enter a valid name';
return false;
}
return true;
}
</script>
</head>
<body>
Name: <input type="text" id = "Name"> <span id = "nameerror"> </span>
<br></br>
Email: <input type="text" id = "Email">
<br></br>
Website: <input type="text" id = "Website">
<br></br>
Comnent: <textarea cols="35" rows="7" id="Comment"> </textarea>
<br></br>
<input type="submit" onclick="showMessage()" value="submit" />
<p>Name: <span id = "displayname"></span> </p>
<p>Email: <span id = "displayemail"></span> </p>
<p>Website: <span id = "displaywebsite"></span> </p>
<p>Comment: <span id = "displaycomment"></span> </p>
</body>
</html>
<form action="" name="form" onsubmit="return validate()">
<tr>
<td align="right">Name:<font color="red">*</font>
</td>
<td>
<input type="text" name="Name" /> <span id="MITname"> </span>
</td>
</tr>
<br/>
<input type="button" value="Submit" onclick="showinput()" />
<br/>
<label>Your input:</label>
<p><span id="namedisplay"></span>
</p>
</form>
Just remove type='submit' in your code it will submit your page while click once you click submit the data's are change to POST , So use button as type
Related
I wrote a simple script to check my form data upon submission. However it's not supposed to keep sending if the inputs are empty. Why isn't it working?
<script src="scripts/formvalidate.js"></script>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" id="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" id="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" id="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" id="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var result = false;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementById("label").innerHTML = output;
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
result = true;
}
return result;
}
You can't use multiple elements with the same id's since an Id is supposed to identify a uniquely an element of the page (HTML5 Specification says: ID must be document-wide unique.), try to use classes instead, and change your getElementById() to getElementsByClassName() just like this and it should work fine:
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementsByClassName("label").innerHTML = output; //notice how I changed the function used here
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
return true;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="formvalidate.js"></script>
<title></title>
</head>
<body>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" class="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" class="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" class="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" class="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
</body>
</html>
Note that the asterisk you try to insert, is only inserted in one input for the same reason noted before (multiple ID's are senseless to the DOM). as the DOM tries to fix that, it only get's the first element on the document with the given id (to fix it just change id="asterisk" types to class="asterisk" type).
Plot twist: the reason you probably didn't see any error screen was because (I guess) you were testing it on chrome, which only shows the error for a millisecond. my personal advise is to use firefox for testing purposes, since it won't hide any error at all.
I made a tool which make my work a little easier by inserting a value into a url in a new window on multiple sites. It was working quite well but now I am having the problem of the search value being cleared onsubmit.
Javascript:
<script language="JAVASCRIPT">
function run() {
var request = document.text.query.value;
var req = "";
var endofurl = "endofurl.html";
for(var i = 0; i < request.length; i++) {
var ch;
if((ch = request.substring(i, i + 1)) == " ") req += " ";
else req += ch;
}
if(document.search.website.checked) {
var website = open( "https://www.website.com/" + req, "website");
}
//--></script>
HTML:
<form name="search">
Please select the networks you want to use.
<p>
</center>
</p>
<div class="row">
<div class="column">
<br>
<input name="website" type="checkbox">Website to Search
<form name="text" onsubmit="run(); return false;">
<center>And enter your Query.</center>
<center>
<input name="query" placeholder="Steropodon" value="" size="50" type="TEXT">
<input value="Search" onclick="run()" type="BUTTON">
</center>
So far, return false had been working to keep the value of the input in the form="text" input name="query" but now it seems to clear it and reload the page. I'm not sure what changed.
You have errors in your code opening and closing the tags.
Try this code. It works:
<html>
<head></head>
<body>
Please select the networks you want to use
<div class="row">
<div class="column">
<br>
<input name="website" type="checkbox">Website to Search
<form name="text" onsubmit="run(); return false;">
<center>And enter your Query.</center>
<center>
<input name="query" placeholder="Steropodon" value="" size="50" type="TEXT">
<input value="Search" onclick="run()" type="BUTTON">
</center>
</form>
</div>
</div>
<script language="JAVASCRIPT">
function run() {
var request = document.text.query.value;
var req = "";
var endofurl = "endofurl.html";
for(var i = 0; i < request.length; i++) {
var ch;
if((ch = request.substring(i, i + 1)) == " ") req += " ";
else req += ch;
}
var checkbox = document.getElementsByName("website");
if(checkbox[0].checked) {
var website = open("https://www.website.com/" + req,
"website");
}
}
</script>
</body>
</html>
Hope it helps.
I fixed it. It was not the tags. I had only pasted a small amount of the total code to make it easier to read but I failed at making it easier to read. The problem was undefined inputs. I have been adding many if statements but didn't have a corrosponding checkbox. Oops.
Thanks for the help.
I'm trying to use the information that I obtain through a form via a submit button, do a little processing, and print it out onto the web page, preventing it from being submitted to a web server by including (return false).
Here is the code to the page:
<html>
<head>
<title>SmithSellsStuff</title>
</head>
<body>
I'm too cheap to buy something nice
<script>
var myData = {
price: "4.25",
taxRate: "0.07",
shipRate: "0.02"
};
myData.calculateTotal = function() {
myData.name = document.getElementById("name");
myData.date = document.getElementById("date");
myData.numItems = document.getElementById("number of items");
var itemTotal = myData.numItems * myData.price;
var taxTotal = (myData.numItems * myData.price) * myData.taxRate;
var shipTotal = (myData.numItems * myData.price) * myData.shipRate;
document.writeln(itemTotal);
document.writeln(taxTotal);
document.writeln(shipTotal);
};
</script>
<form>
</p>
<label>Name: <input type="text" name="name" id="name" tabindex="1"/> </label>
</p>
<label>Delivery Date: <input type="date" name="date" id="date" tabindex="2"/></label>
</p>
<label>Number of items: <input type="number" name="number of items" id="number of items" tabindex="3"/></label>
</p>
<input type="submit" onclick="calculateTotal(); return false;"/>
</form>
</body>
</html>
On the first page, I have a simple form with a field for name, date, number of items total, and a submit button. One error I'm getting is in the onclick tag. It says '_kof_1' is defined but never used. I don't think it is allowing my calculateTotal function to call.
It's because the function was not declared in the global scope, but rather as a property of myData.
myData.calculateTotal = function() {
To solve this, simply change the call to:
<input type="submit" onclick="myData.calculateTotal(); return false;"/>
Furthermore, since you want to get the name, date, and number of items from the text fields, you have to get the .value property to get the contents of the input fields, like so:
myData.name = document.getElementById("name").value;
myData.date = document.getElementById("date").value;
myData.numItems = parseInt(document.getElementById("number of items").value);
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
I'm too cheap to buy something nice
<script>
function calculateTotal()
{
alert("hai");
var price="4.25";
var taxRate="0.07";
var shipRate="0.02";
var name = document.getElementById("name");
var date = document.getElementById("date");
var numItems = document.getElementById("number_of_items").value;
alert(numItems);
var itemTotal = numItems * price;
var taxTotal = (numItems * price) * taxRate;
var shipTotal = (numItems * price) * shipRate;
document.writeln("Total Items:"+itemTotal+"\tTax :"+taxTotal+"\tshipTotal:"+shipTotal);
}
</script>
<form>
<p>
<label>Name: <input type="text" name="name" id="name" tabindex="1"/> </label>
</p>
<label>Delivery Date: <input type="date" name="date" id="date" tabindex="2"/></label>
<p>
<label>Number of items: <input type="number" name="number_of_items" id="number_of_items" tabindex="10"/></label>
</p>
<input type="submit" onclick="calculateTotal()"/>
</form>
</body>
</html>
alert is just for to know method is calling or not, Hope this will help you
I am attempting to build a string of a user's "interests" that they indicate by checking off radio boxes. When I return the result, there is always an "undefined" prepended to the string of interests. I know that I can get rid of this issue by initializing var interest as an empty string, like so:
var interests ="";
But am unsure if this is the proper way to solve the issue. is there a more optimal data structure for this?
var controlIndex;
var element;
var interests;
var numberOfControls = document.form1.length;
for (controlIndex = 0; controlIndex < numberOfControls; controlIndex++)
{
element = document.form1[controlIndex];
if (element.type == "radio")
{
if (element.checked == true)
{
interests += document.form1[controlIndex].value+"\n";
console.log(interests);
document.getElementById("interests").innerHTML= interests
}
}
}
}
}
<form action="" name="form1">
<h1>Personal Details</h1>
Please enter the following details:
<br>
<p>
First Name:
<br />
<input type="text" name="txtName" onchange="txtName_onchange()"/>
</p>
<p>
Age:
<br />
<input type="text" name="txtAge" size="3" maxlength="3" onchange="textAge_onblur()" />
</p>
<p>
My interest is:
<p>Sports
<input type="radio" name="sports" value="sports"/>
</p>
<p>Politics
<input type="radio" name="politics" value="politics" />
</p>
<p>Magazines
<input type="radio" name="magazines" value="magazines">
</p>
<p>
<input type="button" value="Submit Registration" name="btnCheckForm" onclick="btnCheckForm_onclick()" >
<input type = "button" value = "Clear Details" name="btnClear" onclick="btnClear_onclick()">
</p>
</form>
</div>
I would turn your "interests" variable into an array.
var interests = [];
then I would just push into it, like so. When you want to print it out, just join it.
interests.push(document.form1[controlIndex].value);
console.log(interests.join(""));
But am unsure if this is the proper way to solve the issue ...
Yes, initialising the variable as a string is the proper way to resolve this issue.
Basically, whenever you initialise your variable like this:
var interests;
The variable type is implicitly set to undefined, so when you apply += onto it, JavaScript changes the type to string with a value of "undefined". Setting the initial value prevents that:
var interests = '';
I have tried to put same thing mentioned in above answers in code snippet for better understanding. In my opinion array suits here
function btnCheckForm_onclick (){
var controlIndex;
var element;
//Case with '' intitlization
var interests = '';
//Case with [] intitlization
var interests = [];
var numberOfControls = document.form1.length;
for (controlIndex = 1; controlIndex < numberOfControls; controlIndex++)
{
element = document.form1[controlIndex];
if (element.type == "radio")
{
if (element.checked == true)
{
// Case with []
//interests.push(document.form1[controlIndex].value);
//console.log(interests.join(" "));
//Case with ''
interests += document.form1[controlIndex].value+"\n";
console.log(interests);
}
}
}
document.getElementById("interests").innerHTML= interests
}
<form action="" name="form1">
<h1>Personal Details</h1>
Please enter the following details:
<br>
<p>
First Name:
<br />
<input type="text" name="txtName" onchange="txtName_onchange()"/>
</p>
<p>
Age:
<br />
<input type="text" name="txtAge" size="3" maxlength="3" onchange="textAge_onblur()" />
</p>
<p>
My interest is:
<p>Sports
<input type="radio" name="sports" value="sports"/>
</p>
<p>Politics
<input type="radio" name="politics" value="politics" />
</p>
<p>Magazines
<input type="radio" name="magazines" value="magazines">
</p>
<p>
<input type="button" value="Submit Registration" name="btnCheckForm" onclick="btnCheckForm_onclick()" >
<input type = "button" value = "Clear Details" name="btnClear" onclick="btnClear_onclick()">
</p>
<div id="interests"></div>
This seems repeated question but please take a look and try to answer.
My javascript validation function is not working.
Javascript code is given below:
<script type="text/javascript">
var ck_name = /^[A-Za-z ]{3,20}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}
(?:\. [a-z]{2})?)$/i
var ck_mobile = /^[0-9]{10}$/;
var ck_address = /^[A-Za-z0-9-,]{40,100}$/;
function validate(myform){
var name = myform.fullname.value;
var email = myform.email.value;
var mobile = myform.mobile.value;
var address = myform.address.value;
var errors = [];
if (!ck_name.test(name)) {
errors[errors.length] = "Enter valid Name .";
}
if (!ck_email.test(email)) {
errors[errors.length] = "You must enter a valid email address.";
}
if (!ck_username.test(mobile)) {
errors[errors.length] = "Enter valid 10 digit mobile number .";
}
if (!ck_password.test(address)) {
errors[errors.length] = "You must enter a valid address min 40 char.";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors){
var msg = "Please Enter Valid Data...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
I have two button 1)submit and 2)cancel
I want when i click submit button,validate function will call and when i click cancel it goes to back to the page.
HTML form
<form action="addorder.php" method="post" enctype="multipart/form-data" name="myform" >
<!-- Form -->
<div class="form">
<?php
if(isset($_SESSION['msg']))
{
?>
<div class="msg msg-ok"><strong><?php echo $_SESSION['msg'];?></strong></div>
<?php } ?>
<label>Full name<span>(Required Field)</span></label>
<input type="text" name="fullname"class="field size1"/>
</p>
<p>
<label>Email<span> (Required Field)</span>
<input type="text" class="field size1" name="email"/>
</label>
</p>
<p>
<label>Mobile<span>(Required Field)</span>
<input type="text" class="field size1" name="mobile"/>
</label>
</p>
<p>
<label>Address<span>(Required Field)</span>
<textarea class="field size1" name="address" rows="3" cols="10"> </textarea>
</label>
</p>
</div>
<!-- End Form -->
<!-- Form Buttons -->
<div class="buttons" >
<input type="submit" name="submit" class="button" value="Submit" onclick="return validate(myform)" />
<input type="submit" name="cancel" class="button" value="Cancel" />
</div>
<!-- End Form Buttons -->
</form>
I tried your code in a jsfiddle, and it wasn't calling validate. Removing most of your javascript and leaving just a basic validate did call validate. So I think your javascript has syntax errors and the form is ignoring it before submitting. So:
Change the cancel button to type=button, so that it doesn't default to submitting the form when you mean to cancel the submission.
Open firebug, or at the very least the javascript console (in some browsers called the 'error console') and look at the errors you get.
Learning how to debug the javascript will help this time and in the future. Javascript can be completely discarded by the browser if there are syntax errors, in which case your form will just submit as though there was no javascript at all.
Don't see that as a suggestion to only submit via javascript, however, as that would prevent users with javascript switched off from being able to use your form. But that cancel-button-that-submits has to go.