JavaScript input value does not restart [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am resetting my input value in the end of my function but I can't figure it out why it does not work? Is it the problem with my HTML or I made a dumb mistake in my script code?
function send() {
var name = document.getElementById('name').value;
var surname = document.getElementById('surname').value;
var mail = document.getElementById('email').value;
var age = document.getElementById('age').value;
var text = document.getElementById('text');
if (!name || !surname || !mail) {
alert("Enter all values");
text.value = "False input";
return;
} else {
var con = "You sur ?";
if (confirm(con)) {
text.value = "Good input";
}
}
//Here i restart the inputs
console.log(name);
name.value = "";
console.log(name);
surname.value = "";
email.value = "";
}
<form action="">
<div>
<label>Ime</label>
<input type="text" id="name">
</div>
<div>
<label>Prezime</label>
<input type="text" id="surname">
</div>
<div>
<label>Email</label>
<input type="text" id="email">
</div>
<div>
<label>Age</label>
<select name="age" id="age">
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
</select>
</div>
</form>
<div><input type="button" id="btn" value="Prati" onclick="send();"></div>
<div><input type="text" id="text" disabled></div>

Have you tried running reset() on your form?
The HTMLFormElement.reset() method restores a form element's default values.
<form id="myForm">
function myFunction() {
document.getElementById("myForm").reset();
}

The problem is that you're getting the value of the inputs into your name, surname, etc. variables, but then trying to set .value on those variables. The variables contain strings, not elements.
You have two options:
Save the elements, not values, to the variables
Save the elements to the variables instead of the values, so you can use the elements at the end as well, see comments:
function send() {
// No `.value` on these, so we get the elements
var name = document.getElementById('name');
var surname = document.getElementById('surname');
var mail = document.getElementById('email');
var age = document.getElementById('age');
var text = document.getElementById('text');
// Include `.value` here
if (!name.value || !surname.value || !mail.value) {
alert("Enter all values");
text.value = "False input";
return;
} else {
var con = "You sur ?";
if (confirm(con)) {
text.value = "Good input";
}
}
// Reset the inputs
console.log(name.value);
name.value = "";
console.log(name.value);
surname.value = "";
email.value = "";
}
<form action="">
<div>
<label>Ime</label>
<input type="text" id="name">
</div>
<div>
<label>Prezime</label>
<input type="text" id="surname">
</div>
<div>
<label>Email</label>
<input type="text" id="email">
</div>
<div>
<label>Age</label>
<select name="age" id="age">
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
</select>
</div>
</form>
<div><input type="button" id="btn" value="Prati" onclick="send();"></div>
<div><input type="text" id="text" disabled></div>
Use the reset method
However, if you just want to reset the inputs to their default value from the HTML, you can use the form's reset method instead. To do that, I'd put the button inside the form, and use modern event handling; see comments:
// Use modern event handling
document.getElementById("btn").addEventListener("click", send);
function send() {
var name = document.getElementById('name').value;
var surname = document.getElementById('surname').value;
var mail = document.getElementById('email').value;
var age = document.getElementById('age').value;
var text = document.getElementById('text');
if (!name || !surname || !mail) {
alert("Enter all values");
text.value = "False input";
return;
} else {
var con = "You sur ?";
if (confirm(con)) {
text.value = "Good input";
}
}
// Here, `this` will refer to the button. Find the `form` it's in...
const form = this.closest("form");
// ...and reset it
form.reset();
}
<form action="">
<div>
<label>Ime</label>
<input type="text" id="name">
</div>
<div>
<label>Prezime</label>
<input type="text" id="surname">
</div>
<div>
<label>Email</label>
<input type="text" id="email">
</div>
<div>
<label>Age</label>
<select name="age" id="age">
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
</select>
</div>
<!-- Move button into the form -->
<div><input type="button" id="btn" value="Prati"></div>
</form>
<div><input type="text" id="text" disabled></div>

Use this. You can trigger your form id.
document.getElementById("client").reset();
Check this out: How to reset (clear) form through JavaScript?

Related

Why doesn't Javascript validate my html code?

This is my first attempt at working with javascript and forms; for some reason my html website elements aren't being validated and I am not sure why. My goal with this form is trying to validate the elements that have an '*' next to them. For some reason the only element that is being validated is email and nothing else. Name, dates, the checkbox aren't. I have been trying to find a fix, but nothing seems to work.
<!doctype html>
<html>
<head>
<link href="styles.css" rel="stylesheet">
<script src="script.js"></script>
<meta charset="utf-8">
<title>Form</title>
</head>
<body>
<div class="container">
<h1>Travel Reservation Form</h1>
<h4>* denotes mandotory field</h4>
<form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post">
<fieldset>
<legend>Personal Details</legend>
<label class="align">Full name:<span>*</span></label> <input type="text" name="fullname" placeholder="James Bond">
<br><br>
<label class="align">Email<span>*</span></label>
<input type="email" name="mail" placeholder="james#gmail.com">
<br><br>
<label class="align">Date of Birth<span>*</span></label> <input type="date" name="DOB" placeholder="dd/mm/yy">
</fieldset>
<br>
<label>Select Tour Package<span>*</span>:</label>
<select name="package">
<option value="1">Tokyo</option>
<option value="2">Shanghai</option>
<option value="3">Bangkok</option>
<option value="4">Jakarta</option>
<option value="5">Mumbai</option>
</select>
<label>Number of persons<span>*</span>:</label>
<select name="party">
<option value="1">One Adult</option>
<option value="2">Two Adults</option>
<option value="3">Three Adults</option>
<option value="4">Four Adults</option>
<option value="5">Five Adults</option>
</select>
<br><br>
<label>Arrival Date<span>*</span>:</label> <input type="date" name="arrival" placeholder="dd/mm/yy">
<br><br>
<p>What Intrests you the most?<span>*</span>:</p>
<input class="alignp" type="checkbox" name="interest" value="shopping"> Shopping <br><br>
<input class="alignp" type="checkbox" name="interest" value="dining"> Dining <br><br>
<input class="alignp" type="checkbox" name="interest" value="dancing"> Dancing <br><br>
<input class="alignp" type="checkbox" name="interest" value="SightS"> Sightseeing <br><br><br>
<label>Discount Coupon code:</label> <input type="text" name="dis_code" value=""><br><br>
<label>Terms and Conditions<span>*</span><input type="radio" name="tos" value="yes" checked>I agree</label>
<input type="radio" name="tos" value="yes">I disagree
<p>Please provide any additional information below:- </p>
<textarea name="message" rows="5" cols="45" placeholder="Please type here...."></textarea><br><br>
<button class="btn-submit" type="submit" value="Submit">Submit</button>
<button class="btn-reset" type="reset" value="Reset">Reset</button>
</form>
</div>
</body>
</html>
Here is the javascript that is being linked in the html. I am unsure whether the issue is with my html code or with my javascript.
// JavaScript Document
function validateForm()
{
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var dob = document.forms["myForm"]["DOB"].value;
var packages = document.forms["myForm"]["package"].value;
var arrival = document.forms["myForm"]["arrival"].value;
//var interest = document.forms["form"]["interest"].value;
var ToS = document.forms["myForm"]["tos"].value;
var checkbox = document.querySelector('input[name="interest"]:checked');
var matches = name.match(/\d+/g);
if (matches != null) {
alert("Name has a number in it!");
}
if (name == "") {
alert("Name must be filled out");
return false;
}
if (email == "") {
alert("Email must be filled out");
return false;
}
if (dob == "") {
alert("Date of Birth must not be empty");
return false;
}
if (arrival == "") {
alert("Arrival Date must not be empty");
return false;
}
if(ToS == false) {
alert("You must agree to the Terms of Service");
return false;
}
if(validateEmail(email) == false){
alert("Must enter a valid email");
}
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if(dob != '' && !dob.match(re)) {
alert("Invalid date format");
return false;
}
if(arrival != '' && !arrival.match(re)) {
alert("Invalid arrival date format") ;
return false;
}
if(name.length >= 30){
alert("Name must be less than 30 characters!");
return false;
}
if(!checkbox){
alert("Please select an interest!");
return false;
}
}
function validateEmail(email)
{
return /\S+#\S+\.\S+/.test(email);
}
So I have no idea what your PHP form did, so I actually just pulled all the form code for now. There were a lot of little issues but honest mistakes. Example: you don't want a return statement after every validation if you want to continue validating the rest of the fields. I combined some separate validations into if/else's since they were validations on the same field. I used ID's to make my life easier and since I dumped the form code. Feel free to swap back to what you want. I also updated your regex since the date field returns YYYY/MM/DD. Since this doesn't post anywhere you can play with it for a while, before tying back into your php form. I also pulled the check for 30 characters and added a max field length to name. You could also set min and max date ranges for the date fields and a bunch of other things to help make the fields themselves more foolproof. There are also libraries that handle this kind of thing for you, you don't have to re-invent the wheel, but if you're just looking to play around with it this should get you started. Good Luck
<!doctype html>
<html>
<body>
<div class="container">
<h1>Travel Reservation Form</h1>
<h4>* denotes mandotory field</h4>
<fieldset>
<legend>Personal Details</legend>
<label class="align">Full name:<span>*</span></label> <input type="text" name="fullname" id='name' maxlength="30" placeholder="James Bond">
<br><br>
<label class="align">Email<span>*</span></label>
<input id="email" type="email" name="mail" placeholder="james#gmail.com">
<br><br>
<label class="align">Date of Birth<span>*</span></label> <input type="date" id="dob" name="DOB" placeholder="dd/mm/yy">
</fieldset>
<br>
<label>Select Tour Package<span>*</span>:</label>
<select id='package' name="package">
<option value="1">Tokyo</option>
<option value="2">Shanghai</option>
<option value="3">Bangkok</option>
<option value="4">Jakarta</option>
<option value="5">Mumbai</option>
</select>
<label>Number of persons<span>*</span>:</label>
<select name="party">
<option value="1">One Adult</option>
<option value="2">Two Adults</option>
<option value="3">Three Adults</option>
<option value="4">Four Adults</option>
<option value="5">Five Adults</option>
</select>
<br><br>
<label>Arrival Date<span>*</span>:</label> <input type="date" name="arrival" id="arrival" placeholder="dd/mm/yy">
<br><br>
<p>What Intrests you the most?<span>*</span>:</p>
<input class="alignp" type="checkbox" name="interest" value="shopping"> Shopping <br><br>
<input class="alignp" type="checkbox" name="interest" value="dining"> Dining <br><br>
<input class="alignp" type="checkbox" name="interest" value="dancing"> Dancing <br><br>
<input class="alignp" type="checkbox" name="interest" value="SightS"> Sightseeing <br><br><br>
<label>Discount Coupon code:</label> <input type="text" name="dis_code" value=""><br><br>
<label>Terms and Conditions<span>*</span>
<input type="radio" name="tos" id="accpeted" value="agree" checked>I agree</label>
<input type="radio" name="tos" id="unaccepted" value="disagree">I disagree
<p>Please provide any additional information below:- </p>
<textarea name="message" rows="5" cols="45" placeholder="Please type here...."></textarea><br><br>
<button class="btn-submit" id="submit" onclick="return validateForm()">Submit</button>
</div>
<script>
// JavaScript Document
function validateForm() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var dob = document.getElementById("dob").value;
//Select Box
var e = document.getElementById("package");
// Selected Item
var packages = e.options[e.selectedIndex].value;
var arrival = document.getElementById("arrival").value;
//var interest = document.getElementById("").value;
var tos = document.querySelector('input[name="tos"]:checked').value;
//var checkbox = document.getElementById("").value;;
var matches = name.match(/\d+/g);
var re = /^\d{4}([.\/-])\d{2}\1\d{2}$/;
if (!name) {
alert("Name must be filled out");
} else {
if (matches != null) {
alert("Name has a number in it!: " + name);
}
}
if (!email) {
alert("Email must be filled out");
} else {
if (validateEmail(email) == false) {
alert("Must enter a valid email: " + email);
}
}
if (!dob) {
alert("Date of Birth must not be empty");
} else {
if (!dob.match(re)) {
alert(" Dob has Invalid date format: " + dob);
}
}
if (!arrival) {
alert("Arrival Date must not be empty");
} else {
if (!arrival.match(re)) {
alert(" Dob has Invalid date format: " + arrival);
}
}
if (tos != "agree") {
alert("You must agree to the Terms of Service");
}
}
function validateEmail(email) {
return /\S+#\S+\.\S+/.test(email);
}
</script>
</body>
</html>

Dynamically accesing a button and creating a list Javascript

Alright, so I am stuck. So the break down of the project is when you enter your age, and select an option from the drop down list when you click add, a list is created and that input is plugged into the list. I have to also show that list somewhere on the page. I hope I explained that correctly.
Anyways, I've been trying everything from trying to create a new div, to creating an unordered list programmatically, and trying to display it within the body under the last div, but my code below doesn't execute when I hit the add button. By the way I CAN NOT edit the HTML in anyway and I CAN NOT use JQuery. I have to use pure Javascript. Any tips or help would be great!
var form = document.getElementsByTagName("form")[0];
form.method = "POST";
form.action = "form-handler";
var add = document.getElementsByClassName('add');
add.onlick = 'addToList()';
var age = document.getElementsByName("age")[0];
age.type = "number";
age.required = true;
age.min = "0";
age.max = "120";
var dropDown = document.getElementsByName("rel")[0];
dropDown.type = "option";
dropDown.required = true;
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
//var title = document.createElement("h2");
//title = "Member List";
//newDiv.appendChild(title);*
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
function addToList() {
var li = document.createElement("li");
//li.setAttribute('id', age.value + dropDown.value);
li.appendChild(document.createTextNode(age.value + ' ' + dropDown.value));
ul.appendChild(li);
return false;
}
<h1>Household List</h1>
<div class="builder">
<o class="household"></o>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
There was some syntactical errors in the code, especially the button click event handler. Here is the correct code.
var form = document.getElementsByTagName("form")[0];
form.method = "POST";
form.action = "form-handler";
var add = document.getElementsByClassName('add');
add[0].onclick = addToList;
var age = document.getElementsByName("age")[0];
age.type = "number";
age.required = true;
age.min = "0";
age.max = "120";
var dropDown = document.getElementsByName("rel")[0];
dropDown.type = "option";
dropDown.required = true;
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
//var title = document.createElement("h2");
//title = "Member List";
//newDiv.appendChild(title);*
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
function addToList() {
var li = document.createElement("li");
//li.setAttribute('id', age.value + dropDown.value);
li.appendChild(document.createTextNode(age.value + ' ' + dropDown.value));
ul.appendChild(li);
return false;
}
<h1>Household List</h1>
<div class="builder">
<ol class="household"></o>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
There are numerous issues in your code
All the for attributes and input attributes can be defined the html instead of using js
button type default is submit ,so add button type="button" in <button class="add">add</button>
add.onlick = 'addToList()'; is wrong ;the function is not a string , replace it with document.getElementsByClassName('add')[0].onclick = addToList;
var age = document.getElementsByName("age")[0];
var dropDown = document.getElementsByName("rel")[0];
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
document.getElementsByClassName('add')[0].onclick = addToList;
function addToList() {
var li = document.createElement("li");
li.appendChild(document.createTextNode(age.value + ' ' + dropDown.value));
ul.appendChild(li);
return false;
}
<body>
<h1>Household List</h1>
<div class="builder">
<o class="household"></o>
<form method="POST" action="form-handler">
<div>
<label>Age
<input type="number" name="age" min="0" max="120">
</label>
</div>
<div>
<label>Relationship
<select name="rel" required>
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add" type="button">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
</body>
There is a problem with your HTML you have an o tag instead of an order list tag. This may fix the code. Also when you click on the add button the form is posted so I would remove the post until the end.

Can't keep CSS change via Javascript

I have a simple "select" - show below.
<label>Best way to reach you?</label><br>
<select id="contactMethod">
<option value="wp">Work Phone?</option>
<option value="cp">Personal Cell Phone?</option>
<option value="email">Email?</option>
<option value="Im">Instant Messanger?</option>
</select>
<button onclick="showHidden()">Which way?</button>
the object I wish to show is in the HTML with the following properties:
<label>E-mail Address:</label>
<input id="email" type="text" style='display:none'>
I then have a .js file with the following function.
function showHidden() {
var dropSelection = document.getElementById("contactMethod").value;
console.log(dropSelection)
if(dropSelection == "email") {
document.getElementById("email").style.display = "block";
}
}
I then have the id listed within my CSS as the following:
#email{ display:none; }
The goal is to "show" the email text box when the "email" option is selected from the <select> above.
As of right now, I'm simply printing what was selected, so I can know for sure that I'm getting the right values to run the if statement against. That being said, when I select the email option, it literally flashes the email text box but immediately reverts back to a hidden state.
UPDATED CODE
<label>Best way to reach you?</label><br>
<select onchange="showHidden()" id="contactMethod">
<option value="select">Select...</option>
<option value="email">Email</option>
<option value="phone">Work Phone</option>
<option value="cPhone">Cell Phone</option>
<option value="Im">Instant Messanger</option>
</select>
MODIFIABLE FIELDS
<label id="emailLabel">E-mail Adress:</label>
<input id="email" type="text">
<label id="phoneLabel">Work Phone Number</label>
<input id="phone" type="text">
<label id="cPhoneLabel">Personal Cell Phone Number</label>
<input id="cPhone" type="text">
<label id="IMLabel">Instant Messenger Name</label>
<input id="Im" type="text">
JS
function showHidden() {
var dropSelection = document.getElementById("contactMethod").value;
if(dropSelection == "email") {
document.getElementById("email").style.display = "block";
document.getElementById("emailLabel").style.display = "inline";
}
else if(dropSelection == "phone") {
document.getElementById("phone").style.display = "block";
document.getElementById("phoneLabel").style.display = "inline";
}
else if(dropSelection == "cPhone") {
document.getElementById("cPhone").style.display = "block";
document.getElementById("cPhoneLabel").style.display = "inline";
}
else if(dropSelection == "Im") {
document.getElementById("Im").style.display = "block";
document.getElementById("IMLabel").style.display = "inline";
}
}
function showHidden(){
var dropSelection = document.getElementById("contactMethod").value;
console.log(dropSelection)
if(dropSelection == "email"){
document.getElementById("email").style.display = "block";
}
}
#email{
display:none;
}
<label>Best way to reach you?</label>
<br>
<select id="contactMethod">
<option value="wp">Work Phone?</option>
<option value="cp">Personal Cell Phone?</option>
<option value="email">Email?</option>
<option value="Im">Instant Messanger?</option>
</select>
<br>
<button onclick="showHidden()">Which way?</button>
<br>
<label>E-mail Adress:</label>
<br>
<input id="email" type="text" display="none">
<br>
I don't see any problem, it works fine.

Basic JavaScript validation not working

I'm trying to make a simple form with JavaScript validation. It has four fields: title, email address, rating and comments. As far as I know, the code I have here should work to validate the form and I should not be allowed to submit it but whenever I press the submit button none of the prompts appear and the browser submits the form. Could someone let me know where I am going wrong please? I'd imagine there is a simple solution or something I am forgetting but I'm pretty new to this so apologies if it's something very obvious.
The HTML and JavaScript code is:
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var e=document.forms["review"]["Title"].value;
var s=document.forms["review"]["Email"].value;
var t=document.forms["review"]["Rating"].value;
var c=document.forms["review"]["Comments"].value;
var atsym=s.indexOf("#");
var dotsym=s.lastindexOf(".");
if (e==null || e=="")
{
document.getElementById("valAlert").innerHTML="Please Enter a Title";
return false;
}
else if (s==null || s=="" || atsym<1 || dotsym<atsym+2 || dotsym+2>=s.length)
{
document.getElementById("valAlert").innerHTML="That is not a valid email address!";
return false;
}
else if (t=="0")
{
document.getElementById("valAlert").innerHTML="You must enter a rating";
return false;
}
else if (c==null || c=="")
{
document.getElementById("valAlert").innerHTML="You need to enter some kind of comment.";
return false;
}
else
{
alert ("Your review of " + t + "has been submitted!");
}
}
</script>
</head>
<body>
<div id="valAlert"></div>
<form name="review" onsubmit="return validateForm()">
<fieldset>
Enter Title:
<input type="text" name="Title">
</br>
</br>
Enter Email Address:
<input type="text" name="Email">
</br>
</br>
Please Enter Your Rating:
<select name="Rating">
<option value="0">(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
</br>
</br>
<textarea name="Comments" rows="8" colspan="40">Comments:</textarea>
</fieldset>
</br>
</br>
<fieldset>
<input class="button" type="submit" value="Submit"/>
</fieldset>
</form>
</body>
please make a null value check before doing the operations like below
var dotsym=s.lastindexOf(".");
Add the null check for variable 's'.Please check the function naming convention below
obj.lastindexOf(); TO obj.lastIndexOf(".");
You’ve said there were no errors, but you might just be missing them when the form submits and the console is cleared.
If you’re using Chrome/Chromium, you can enable breaking on exceptions in the Sources tab of the developer tools (the icon on the far right should be purple or blue):
In Firefox, it’s in the Debugger Options menu:
As #Rajesh says, the casing you have on lastindexOf is wrong; it should be lastIndexOf.
Now, let’s fix everything else up, starting with formatting:
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var e = document.forms["review"]["Title"].value;
var s = document.forms["review"]["Email"].value;
var t = document.forms["review"]["Rating"].value;
var c = document.forms["review"]["Comments"].value;
var atsym = s.indexOf("#");
var dotsym = s.lastIndexOf(".");
if (e == null || e == "")
{
document.getElementById("valAlert").innerHTML = "Please Enter a Title";
return false;
}
else if (s == null || s == "" || atsym < 1 || dotsym < atsym + 2 || dotsym + 2 >= s.length)
{
document.getElementById("valAlert").innerHTML = "That is not a valid email address!";
return false;
}
else if (t == "0")
{
document.getElementById("valAlert").innerHTML = "You must enter a rating";
return false;
}
else if (c == null || c == "")
{
document.getElementById("valAlert").innerHTML = "You need to enter some kind of comment.";
return false;
}
else
{
alert("Your review of " + t + " has been submitted!");
}
}
</script>
</head>
<body>
<div id="valAlert"></div>
<form name="review" onsubmit="return validateForm()">
<fieldset>
Enter Title:
<input type="text" name="Title" />
</br>
</br>
Enter Email Address:
<input type="text" name="Email" />
</br>
</br>
Please Enter Your Rating:
<select name="Rating">
<option value="0">(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
</br>
</br>
<textarea name="Comments" rows="8" colspan="40">Comments:</textarea>
</fieldset>
</br>
</br>
<fieldset>
<input class="button" type="submit" value="Submit" />
</fieldset>
</form>
</body>
You’re missing a DTD and a closing </html>, so add those:
<!DOCTYPE html>
<html>
…
</html>
Next, </br> doesn’t exist. It’s <br />.
<form name="review" onsubmit="return validateForm()">
<fieldset>
Enter Title:
<input type="text" name="Title" />
<br />
<br />
Enter Email Address:
<input type="text" name="Email" />
<br />
<br />
Please Enter Your Rating:
<select name="Rating">
<option value="0">(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
<br />
<br />
<textarea name="Comments" rows="8" colspan="40">Comments:</textarea>
</fieldset>
<br />
<br />
<fieldset>
<input class="button" type="submit" value="Submit" />
</fieldset>
</form>
Here:
var e = document.forms["review"]["Title"].value;
var s = document.forms["review"]["Email"].value;
var t = document.forms["review"]["Rating"].value;
var c = document.forms["review"]["Comments"].value;
the properties are valid JavaScript identifiers, so you can write them with the dot syntax:
var e = document.forms.review.Title.value;
var s = document.forms.review.Email.value;
var t = document.forms.review.Rating.value;
var c = document.forms.review.Comments.value;
You should probably give them clearer names, too; I think you used the wrong one in that last alert, and this will help:
var title = document.forms.review.Title.value;
var email = document.forms.review.Email.value;
var rating = document.forms.review.Rating.value;
var comments = document.forms.review.Comments.value;
Next, you don’t need elses when you’re returning from the if case no matter what, so you can drop those. The values of text inputs can never be null, so stop checking for those. It’ll also save some typing (or copying) to keep valAlert as a variable.
var atsym = email.indexOf("#");
var dotsym = email.lastindexOf(".");
var valAlert = document.getElementById("valAlert");
if (title === "") {
valAlert.innerHTML = "Please Enter a Title";
return false;
}
if (atsym < 1 || dotsym < atsym + 2 || dotsym + 2 >= s.length) {
valAlert.innerHTML = "That is not a valid email address!";
return false;
}
if (rating == "0") {
valAlert.innerHTML = "You must enter a rating";
return false;
}
if (comments == "") {
valAlert.innerHTML = "You need to enter some kind of comment.";
return false;
}
alert("Your review of " + title + " has been submitted!");
Voilà! But wait; there’s more. The best things in life web development don’t need JavaScript, and this is no exception.
<!DOCTYPE html>
<html>
<head>
<title>HTML5 validation</title>
</head>
<body>
<form>
<fieldset>
<label>
Enter title:
<input type="text" name="title" required />
</label>
<label>
Enter e-mail address:
<input type="email" name="email" required />
</label>
<label>
Please enter your rating:
<select name="rating" required>
<option>(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
</label>
<textarea name="comments" rows="8" cols="40" placeholder="Comments" required></textarea>
</fieldset>
<fieldset>
<button class="button">Submit</button>
</fieldset>
</form>
</body>
</html>
I beg to differ on your comments. You are getting console errors. Specially, it is erroring out whenever you try to run the parsers on s and s is empty. You need to move the logic into the if clause AFTER you have verified it has a value:
else if (s == null || s == "") {
document.getElementById("valAlert").innerHTML = "Please enter an email address";
return false;
}
else if (s.indexOf("#") < 1 || s.lastindexOf(".") < s.indexOf("#")+ 2 || s.lastindexOf(".")+ 2 >= s.length) {
document.getElementById("valAlert").innerHTML = "This is not a valid email address!";
return false;
}
Here is a Fiddle

Javascript validation working, but the form doesn't submit

I have this form where for example in Type A you can write only numbers that start with 1, and so on:
<form accept-charset="UTF-8" action="verify.php" id="form" method="post">
<label id="type" for="type" class="">Type</label>
<select class="" id="Type" name="type">
<option id="a" value="1">Type A</option>
<option id="b" value="2">Type B</option>
<option id="c" value="3">Type C</option>
<option id="d" value="4">Type D</option>
<option id="e" value="5">Type E</option>
</select>
<label for="type_number" class="inner_text">Type Number</label>
<input name="type_number" type="text" class="false" id="type_number" />
<input type="button" id="Confirm" value="Confirm" />
</form>
And this Javascript:
document.getElementById('Confirm').onclick = function () {
var letter = document.getElementById("type_number").value.match(document.getElementById("Type").value);
if (letter !== null) {
letter = letter[0].toLowerCase();
this.value = letter + this.value.substring(1);
}
else {
alert('Number is not correct!');
}
}
The validation work, but doesn't submit, when a good answer is writed the 'Confirm' get renamed to '1onfirm', only that happen.
Check the jsfiddle too: http://jsfiddle.net/focusoft/hSmFS/1/
Thanks.
Either submit the form in javascript function or change the confirm button type to submit.
change your javascript function
document.getElementById('Confirm').onclick = function () {
var letter = document.getElementById("type_number").value.match(document.getElementById("Type").value);
if (letter !== null) {
letter = letter[0].toLowerCase();
this.value = letter + this.value.substring(1);
document.forms[0].submit();
}
else {
alert('Number is not correct!');
}
}
Change this:
<input type="button" id="Confirm" value="Confirm" />
for this:
<input type="submit" id="Confirm" value="Confirm" />

Categories

Resources