see the following code :
<html>
<head>
<script type="text/javascript">
function validate()
{
fname = f.fn.value;
if(fname!= "abc")
alert("Incorrect name!")
lname = f.ln.value;
if(lname != "xyz")
alert("Incorrect Name!")
paswd = f.pswd.value;
if(paswd<8)
alert("Too short password!")
for(var i=0; i<f.d.length; i++)
{
if(f.d[i].value.checked)
{
document.write(f.d[i].value);
}
}
for(var i=0; i<f.c.length; i++)
{
if(f.c[i].value.checked)
{
alert(f.c[i].value);
}
}
}
</script>
</head>
<body>
<form name="f" onsubmit="validate()">
First Name: <input type = "text" name = "fn"> <br>
Last Name: <input type = "text" name = "ln"> <br>
Password: <input type = "password" name = "pswd"> <br>
E-mail: <input type = "email" name = "mail"> <br>
Degree : <input type = "radio" name = "d" value = 's'> SE
<input type = "radio" name = "d" value = 'c'>CS
<input type = "radio" name = "d" value = 'E'>IT <br>
University
<select name = "uni">
<option value = 'p'>PU</option>
<option value = 'f'>FAST</option>
</select> <br>
CGPA : <input type = "radio" name = "c" value = '3'> >=3.0
<input type = "radio" name = "c" value = '2'> >=2.5 <br>
Browse <input type = "file" name = "uf"> <br>
<input type = "Submit" value = "Submit">
</form>
</body>
</html>
When i press the submit button,I should get a message of
Incorrect name
or
too short password
if the conditions are true but nothing happens, why?
Why the
validate()
function not running?
The Problem
int i
makes no sense. This would be proper Java syntax, but not in Javascript. I think you mean var i
What else?
You have two form tags.
PS
If you're too lazy to open your web browser's console (or if it doesn't have one), just use the try and catch expressions.
I'm too lazy to fix all these issues. Just give me the fixed code
DEMO
First of all:
Just use form once:
<form> // <--- remove this line
<form name="f" onsubmit="validate()">
Second, you're using a mixture of what seems like JAVA and JavaScript, so instead of for(int i, declare your variable with var. Like so:
for (var i = 0; i < f.d.length; i++) { <--- var instead of int
if (f.d[i].value.checked) {
alert(f.d[i].value);
}
}
That should remove all the errors, you could have also seen these errors yourself when using the correct debugging tools. Here is a list of them:
Chrome DevTools: https://developers.google.com/chrome-developer-tools/docs/console
Firebug: http://getfirebug.com/
For Internet Explorer: http://msdn.microsoft.com/en-us/library/ie/dn255006(v=vs.85).aspx
Couple of error in your code
<html>
<head>
<script type="text/javascript">
function validate()
{
fname = document.f.fn.value;
if(fname!= "abc")
alert("Incorrect name!");
lname = f.ln.value;
if(lname != "xyz");
alert("Incorrect Name!");
paswd = f.pswd.value;
if(paswd<8)
alert("Too short password!")
for(i=0; i<f.d.length; i++)
{
if(f.d[i].value.checked)
{
document.write(f.d[i].value);
}
}
for(i=0; i<f.c.length; i++)
{
if(f.c[i].value.checked)
{
alert(f.c[i].value);
}
}
// return false; // use this you don't want to submit form
// return true; //for advancing the form
}
</script>
</head>
<body>
<form action="" name="f" onsubmit=" return validate()">
First Name: <input type = "text" name = "fn"> <br>
Last Name: <input type = "text" name = "ln"> <br>
Password: <input type = "password" name = "pswd"> <br>
E-mail: <input type = "email" name = "mail"> <br>
Degree : <input type = "radio" name = "d" value = 's'> SE
<input type = "radio" name = "d" value = 'c'>CS
<input type = "radio" name = "d" value = 'E'>IT <br>
University <select name = "uni">
<option value = 'p'>PU</option>
<option value = 'f'>FAST</option>
</select> <br>
CGPA : <input type = "radio" name = "c" value = '3'> >=3.0
<input type = "radio" name = "c" value = '2'> >=2.5 <br>
Browse <input type = "file" name = "uf"> <br>
<input type = "submit" value = "Submit">
</form>
</body>
</html>
above code is working
I consider that you are performing validation on this form hence you need to the call the function
return validate();
Now if function return false, the form is not submitted
if function return true, the form is submitted
Do ask for further help , Don't waste my effort's
Related
I'm a beginner in web development and I have an HTML form where a person can add his address , address number, region and postal code . In this form the address and the region have to contain only char letters .
(ex. Lakewood : correct Lakewood13 : error) . If any of these two variables contains a number I have to enter my data again to continue . Else, I move to the next page . I'm a complete beginner in javascript which I need to use to check my variable types and I would appreciate your help with guiding me to solve this problem .
This is my code with my HTML form with the address number and the region which are the variables we need in this problem :
function checkdata(){
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
if(typeof(a.value) === 'string'&&(typeof b.value) ==='string'){
//continue to next page(but how can I check if numbers are in the strings ?)
}
else{
//go back to form and enter again(how can I enter the elements again ? )
}
}
<div class = "form-area" id = "forma">
<form action="/action.page.html" class = "sign-form" >
<div class = "form-container">
<h1> Enter purchase data below : </h1>
<label for="addrs"> Address Name</label>
<input type = "text" placeholder = "Enter address name " id = "address" name = "addr" required/>
<label for="regn" > Region </label>
<input type = "text" placeholder = "Enter region " id = "region" name = "reg" required/>
</div>
<button type="submit" class="continuebtn" onclick = "checkdata()">Continue</button>
</form>
</div>
Thank you in advance .
You can try using regex to check if string contains any number in it:
if(!(/\d/.test(a.value)) && !(/\d/.test(b.value))){
Please Note: You also have to return false to prevent the default event if the condition is false and prefix return the function call in onclick attribute.
Demo:
function checkdata(){
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
if(!(/\d/.test(a.value)) && !(/\d/.test(r.value))){
alert('form submit');
}
else{
alert('no submit');
return false;
}
}
<div class = "form-area" id = "forma">
<form action="/action.page.html" class = "sign-form" >
<div class = "form-container">
<h1> Enter purchase data below : </h1>
<label for="addrs" Address Name</label>
<input type = "text" placeholder = "Enter address name " id = "address" name = "addr" required/>
<label for="regn" > Region </label>
<input type = "text" placeholder = "Enter region " id = "region" name = "reg" required/>
</div>
<button type="submit" class="continuebtn" onclick = "return checkdata()">Continue</button>
</form>
</div>
You can write a function for validity, then you can check for dependencies based on that **
function checkData() {
let adress = document.getElementById('address');
let region = document.getElementById('region');
function isValid(e) {
let isTrue;
for (let char in e) {
typeof e[char] !== 'string' ? alert('Please only type strings') : (isTrue = true);
}
return isTrue;
}
isValid(adress.value) && isValid(region.value) ? console.log('next page') : console.log('error');
}
checkData();
**
So need to check if the strings are containing numbers or not
hope you find more insight here: Check whether an input string contains a number in javascript
working demo :
// check if string contains number
function hasNumber(myString) {
return /\d/.test(myString);
}
function checkdata(e) {
e.preventDefault()
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
var isAddressContainsNumber = hasNumber(a.value);
var isRegionContainsNumber = hasNumber(r.value);
console.log(isAddressContainsNumber, isRegionContainsNumber)
if (isAddressContainsNumber === false && isRegionContainsNumber === false) {
console.log('None of string contains number')
} else {
console.log('One or Both string contains number')
}
}
const form = document.querySelector('.sign-form');
form.addEventListener('submit', checkdata);
<div class="form-area" id="forma">
<form class="sign-form">
<div class="form-container">
<h1> Enter purchase data below : </h1>
<label for "addrs" Address Name</label>
<input type="text" placeholder="Enter address name " id="address" name="addr" required/>
</label>
<label for "regn" > Region </label>
<input type="text" placeholder="Enter region " id="region" name="reg" required/>
</label>
</div>
<button type="submit" class="continuebtn">Continue</button>
</form>
</div>
I would recommend going through the string and getting the ASCII value of each character. Numbers 0-9 are ASCII characters 48-57. Javascript uses UTF-16 and the appropriate method (charCodeAt) returns a 16-bit UTF-16 value, but UTF-16 characters 0-127 match ASCII. So:
var testString = "abcd123";
var isValid = true;
for (var i=0;i<testString.length;i++)
{
if (testString.charCodeAt(i) > 47 && testString.charCodeAt(i) < 58)
{
isValid = false;
}
}
if (!isValid)
{
//Code here to alert the user
alert("There's a number in there!");
}
You are using typeof in wrong way, try this way
typeOf(variable you want to check)
I have a form in an html page that ends up being cleared after i click the submit button. I wanted to know how I to make the data stay in the form after clicking submit in case the user needs to fix any errors. Any help would be appreciated!
Here is the html code:
<form id = "contactform" action = "">
<label> Name:
<input name = "firstname" type = "text" id = "firstname" maxlength = "50"/>
</label>
<label> Last Name:
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address:
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode:
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<input type = "submit" value = "Submit" onclick = "validate()" />
<input type = "reset" value = "Clear" />
</p>
</form>
and here is the javascript code:
function validate() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
if(firstname.value == "") {
alert("Make sure the first name field is filled");
return false;
}
if(lastname.value == "") {
alert("Make sure the last name field is filled");
return false;
}
if(address.value == "") {
alert("Make sure the address field is filled");
return false;
}
if(postcode.value == "") {
alert("Make sure the post code field is filled");
return false;
}
First, add a submit handler to your form:
<form id="contactform" action = "" onsubmit="handleSubmit()">
...
</form>
Then in your handler validate the input. If its not valid you need to preventDefault() to stop the form from submitting. Note: You'll have to return true at the end of validate() if nothing is wrong. I don't see that in the question.
function handleSubmit(event) {
if(!validate()) {
event.preventDefault();
}
return;
}
Add return with onclick onclick="return validate()"
function validate() {
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
if (firstname.value == "") {
alert("Make sure the first name field is filled");
return false;
}
if (lastname.value == "") {
alert("Make sure the last name field is filled");
return false;
}
if (address.value == "") {
alert("Make sure the address field is filled");
return false;
}
if (postcode.value == "") {
alert("Make sure the post code field is filled");
return false;
}
}
<form id="contactform" action="">
<label> Name:
<input name = "firstname" type = "text" id = "firstname" maxlength = "50"/>
</label>
<label> Last Name:
<input name = "lastname" type = "text" id = "lastname" maxlength = "150" />
</label>
<label> Address:
<input name = "address" type = "text" id = "address" maxlength = "200"/>
</label>
<label> Postcode:
<input name = "postcode" type = "text" id = "postcode" maxlength = "50" />
</label>
<input type="submit" value="Submit" onclick="return validate()" />
<input type="reset" value="Clear" />
</form>
I am trying to make a form. I want it to check the radio buttons to see if they have been clicked, and if not to have a message to the user to check one.
I tried to just enter it, then I tried to continue my else if statements with it (got error messages), then I tried making a function within the onsubmit function (it simply didn't initiate), then I tried making a function outside of the onsubmit function and am trying to call it, but it does not initiate. I've even tried moving the functions on top or below the onsubmit function.
I made the submitYesCancel to see if the problem was with the radioB function, but neither function will initiate.
I'm hopelessly stuck. Please help.
Here is the code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title></title>
<script type="text/javascript">
/* <![CDATA[ */
function confirmPassword()
{
if (document.forms[0].password_confirm.value != document.forms[0].password.value)
{
window.alert("You did not enter the same password!");
document.forms[0].password.focus();
}
}
function submitForm()
{
submitYesCancel();
if (document.forms[0].name.value == ""
|| document.forms[0].name.value == "Your Name")
{
window.alert("You must enter your name.");
return false;
}
else if (document.forms[0].emailAddress.value == ""
|| document.forms[0].emailAddress.value == "Your Email")
{
window.alert("You must enter your email address.");
return false;
}
else if (document.forms[0].password.value == ""
|| document.forms[0].password_confirm.value == "")
{
window.alert("You must enter a password.");
return false;
}
else if (document.forms[0].sq.value ==""
|| document.forms[0].sq.value == "Your Security Answer")
{
window.alert("You must enter a security answer.");
return false;
}
radioB();
return true;
}
function submitYesCancel()
{
var submitForm = window.confirm("Are you sure you want to submit the form?");
if (submitForm == true)
{
return true;
return false;
}
}
function radioB()
{
var radioButton = false;
for (var i = 0; i < 4; ++i)
{
if (document.forms[0].special_offers[i].checked == true)
{
radioButton = true;
break;
}
}
if (radioButton != true)
{
window.alert("You must select a radio button.");
return false;
}
}
function confirmReset()
{
var resetForm = window.confirm("Are you sure you want to reset the form?");
if (resetForm == true)
return true;
return false;
}
/* ]]> */
</script>
</head>
<body>
<form>
<h2>Personal Information</h2>
<p>Name:<br />
<input type = "text" name = "name" placeholder = "Your Name" size = "50"/></p>
<p>Email Address:<br />
<input type = "text" name = "emailAddress" placeholder = "Your Email" size= "50" /></p>
<h2>Security Information</h2>
<p>Please enter a password of 8 characters or less: <br />
<input type = "password" name = "password" maxlength = "8" /></p>
<p>Confirm password<br />
<input type = "password" name = "password_confirm" size = "50" onblur = "confirmPassword();" /></p>
<p>Please Select a Security Question from the Drop Down List.<br />
<select name = "Security Question">
<option value = "mother">What is your Mother's maiden name?</option>
<option value = "pet">What is the name of your pet?</option>
<option value = "color">What is your favorite color?</option>
</select></p>
<p><input type = "text" name = "sq" placeholder = "Your Security Answer" size = "50" /></p>
<h2>Preferences</h2>
<p>Would you like special offers sent to your email address?<br />
<input type = "radio" name = "radioButton" value = "Yes" />Yes<br />
<input type = "radio" name = "radioButton" value = "No" />No<br /></p>
<p>Are you interested in special offers from: <br />
<input type = "checkbox" name = "sCheckboxes" value = "e" />Entertainment<br />
<input type = "checkbox" name = "sCheckboxes" value = "b" />Business<br />
<input type = "checkbox" name = "sCheckboxes" value = "s" />Shopping<br /></p>
<button onclick="return submitForm();">Submit</button>
<button onclick="return confirmReset();">Reset</button>
</form>
</body>
</html>
The reason that it does not work because your Javascript is completely wrong.
}
radioB();
else // <--- what does it mean?
return true;
And
else if (radioButton ! = true) {
// <-- you have else if, but there is no if block and it is != not ! =
Next time when your Javascript does not work, try to see the error first. You can easily do this in Google Chrome. Hit Ctrl + Shift + J, go to Console tab. Then, fix each error when you encounter it until there is no more error.
I have to do a MC question with radio button. Each question is required to be choice one answer only. Each question has three choices. I want to check whether the user answers every question. If yes, able the submit button. If no, disable the submit button.
Here is my code:
<form name ='form' method ='post' action ='getResult' id ='form'>
Q1. XXXXXXXXXX
<br>
<Input type = 'Radio' Name ='option_1' value= '1'> A1 <br>
<Input type = 'Radio' Name ='option_1' value= '2'> A2 <br>
<Input type = 'Radio' Name ='option_1' value= '3'> A3 <br>
Q2. XXXXXXXXXX
<br>
<Input type = 'Radio' Name ='option_2' value= '1'> A1 <br>
<Input type = 'Radio' Name ='option_2' value= '2'> A2 <br>
<Input type = 'Radio' Name ='option_2' value= '3'> A3 <br>
<Input type = 'Reset' Name = 'Reset' VALUE = 'Reset'>
<Input type = 'Submit' Name = 'submitorder' VALUE = 'Submit' id='submitorder' disabled='disabled'>
</form>
I just make it simple on the content of the question, answer and the value of button.
Try this
$(function(){
$("input[type='radio']").change(function () {
the_value = getChecklistItems();
if(the_value=="2")
$("#submitorder").removeAttr('disabled');
else
$("#submitorder").prop('disabled',true);
});
$("#reset").click(function(){
$("#submitorder").prop('disabled',true);
});
});
function getChecklistItems() {
var count=0;
var result =
$("input:radio:checked").get();
var columns = $.map(result, function(element) {
count=count+1;
});
return count;
}
HTML Change, assign some id to reset button like as below:
<Input type = 'Reset' Name = 'Reset' id="reset" VALUE = 'Reset'>
Demo
I've looked over a number of posts that are similar to my query, but in general, they are not helping me. I think part of my problem is that I am so new to JavaScript that a lot of the previous posts are too complicated for me. I have the simple code below, but it does not seem to work. I do not get my alerts, and I do not think the form is being submitted even when the function should be returning "true." I checked the Error Console, and there are no errors. Can someone help?
JavaScript:
function submit()
{
var age = document.Message.Age.value;
if (age > 39)
{
alert("You're old.");
return false;
}
else
{
alert("You're young!");
return true;
}
}
HTML:
<FORM id = "Message" name = "Message" method = "post" action = "http://cnn.com" onsubmit = "return submit();">
First Name: <INPUT type = "text" name = "Fname"/><br>
Age: <INPUT type = "text" name = "Age"/><br>
<INPUT type="button" name = "Submit" value = "Submit">
</FORM>
Change your HTML to
<FORM id = "Message" name = "Message" method = "post" action = "http://cnn.com" onsubmit = "return submit();">
First Name: <INPUT type = "text" name = "Fname"/><br>
Age: <INPUT type = "text" name = "Age"/><br>
<INPUT type="submit" name = "Submit" value = "Submit">
</FORM>
Note that the input type has been changed to 'submit', so that the submission actually takes place.
I doubt your javascript function itself is being called or not. If not, I think you need to move you onsubmit to <body> tag from <form> tag.
as
<body onsubmit"return submit();">
Also either change your button to either type as submit or add an onClick() event below:
<INPUT type="submit" name = "Submit" value = "Submit"/>
or
<INPUT type="button" name = "Submit" value = "Submit" onClick="submit()"/>
Below is the full working code(in chrome and IE8) sample:
<Html>
<head>
<script language="javascript">
function submit(){
var age = document.Message.Age.value;
if (age > 39){
alert("You're old.");
return false;
}else{
alert("You're young!");
return true;
}
}
</script>
</head>
<body>
<FORM id = "Message" name = "Message" method = "post"
action = "http://cnn.com" onSubmit = "javascript:return submit();">
First Name: <INPUT type = "text" name = "Fname"/><br>
Age: <INPUT type = "text" name = "Age"/><br>
<INPUT type="submit" name = "Submit" value = "Submit"/>
</FORM>
</body>
</html>