This is a question from my elder brother's question paper which I'm trying to solve but I am not able to do so .
Create a form containing a two Text fields and radio button and submit button. Name the
text fields account number and amount and radio button as transaction (deposit ,withdraw
and enquiry).Write a JavaScript the validates the text field to have only numbers, the first
text field should be of size 10 and second text field should have values between 500 to
20,000. Using onclick event a jQuery is called that performs necessary transactions and
display the updated value.
.............................................................................
So I have written the following code:
form1.html
<!DOCTYPE html>
<html>
<head>
<title>Web Tech DA 1</title>
<script type="text/javascript" src="script1.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#sub').click(function() {
var acc=document.getElementById("acc").value;
var amt=document.getElementById("amt").value;
var bal=acc%100;//balance , I am using this to dynamically generate a new balance each time a new account number is entered
$("#t1").click(function(){
bal=acc+amt;
alert(bal);
});
$("#t2").click(function(){
if(acc>amt){
bal=acc-amt;
alert(bal);
}
else{
alert('Insufficient Funds.');
}
});
$("#t3").click(function(){
alert(bal);
});
});
});
</script>
</head>
<body>
<form name="myform" onsubmit="if(validateform()) {window.alert('succefully submitted')} else {return false;}" >
<p>Account Number : <input type="text" maxlength="10" name="acc" id="acc" height="20px" width="100px" required="required" onblur="validacc(this.value)"></p>
<p>Amount : <input type="text" name="amt" id="amt" height="20px" width="100px" required="required" onblur="validamt(this.value)"></p>
<p>Transaction : <input type="radio" name="trans" id="t1" value="deposit" />Deposit
<input type="radio" name="trans" id="t2" value="withdraw" />Withdraw
<input type="radio" name="trans" id="t3" value="enquiry" />Enquiry </p>
<input type="submit" name="sub" id="sub" value="Submit">
</form>
</body>
main1.css
*{
margin:0;
padding: 0;
}
body{
margin: 25px;
}
form p {
margin: 10px;
}
form input {
margin: 10px;
}
script1.js
function validateform() {
var acc = document.getElementById("acc").value.trim();
var amt = document.getElementById("amt").value.trim();
if(validregno(acc)&&validname(amt))
{window.alert("No errors found");return true;}
else
{window.alert("invalid entries found");return false;}
}
// Overall Go
function validacc(r)
{
var p = new RegExp(/^[0-9]{10}$/i);
if(!p.test(r))
{
chngborder("acc");
return false;
}
chngborderr("acc");
return true;
}
function validamt(amt)
{
var p = new RegExp( /^[0-9]{1,}$/);
if(amt>=500 && amt<=20000){
if(p.test(n))
{
chngborderr("amt");
return false;
}
else
{
chngborder("amt");
return true;
}
}
chngborder("amt");
return false;
}
function chngborder(i)
{
document.getElementById(i).style.borderColor="red";
}//red color means wrong format
function chngborderr(i)
{
document.getElementById(i).style.borderColor="green";
}//green color means correct format
For some reason I'm not able to enter a number in the "Amount" text field and none of the radio buttons are working .
Please point out any mistakes that I have done here .
P.S. I'm new to jQuery and form validation
UPDATE
I made the changes pointed out and even then for some reason the "Amount" text field doesn't get validated and the "submit" button resets the form .
I am analysing your code. if this is exactly what you have, I can notice that
1 - You did not include jQuery library in the of you.
you can do it by adding <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> or <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script> inside the <head> element
2 - I think it is better to add and Else in onsubmit event of #myForm
if(validateform()) window.alert('succefully submitted'); else return false.
3 - I have never seen a javascript (.js files) variable declaration starting by int: they start with var keyword regardless the type of the variable
Here is a working code.
script1.js
function validateform() {
var accValue = document.getElementById("acc").value.trim();
var amtValue = document.getElementById("amt").value.trim();
if (validacc(accValue) && validamt(amtValue))
{ window.alert("No errors found"); return true; }
else
{ window.alert("invalid entries found"); return false; }
}
// Overall Go
function validacc(r) {
var p = new RegExp(/^[0-9]{10}$/i);
if (!p.test(r)) {
chngborder("acc");
return false;
}
chngborderr("acc");
return true;
}
function validamt(amt) {
var p = new RegExp(/^[0-9]{1,}$/);
var amtValue = document.getElementById("amt").value;
if (amtValue >= 500 && amtValue <= 20000) {
if (p.test(n)) {
chngborderr("amt");
return false;
}
else {
chngborder("amt");
return true;
}
}
chngborder("amt");
return false;
}
function chngborder(i) {
document.getElementById(i).style.borderColor = "red";
}//red color means wrong format
function chngborderr(i) {
document.getElementById(i).style.borderColor = "green";
}
//Script inside your html file
$(document).ready(function () {
$('#sub').click(function() {
var accValue = document.getElementById("acc").value;
var amtValue = document.getElementById("amt").value;
var bal = accd % 100;})
$("#t1").click(function(){
bal = Number(document.getElementById("aac").value) +
Number(document.getElementById("amt").value);
alert(bal);
});
$("#t2").click(function(){
if(acc > amt){
Number(document.getElementById("aac").value) +
Number(document.getElementById("amt").value);
alert(bal);
}
else{
alert('Insufficient Funds.');
}
});
});
Related
I'm creating a simple JS validation for my form. I need it to highlight red onblur when not filled out, and green once you fill it in afterwards. Sorry, not allowed to imbed images in my posts yet :L
Any help appreciated, thank you.
This is the Html:
<form id="surveyForm">
Favourite movie?
<input type="text" id="favMov" onblur="return $formValidation()"/>
<span id="errorStyle"></span>
</form>
This is the Js:
function $formValidation(elem) {
//gather the calling elements value
var val = document.getElementById(elem.id).value;
//Just for testing - alert(val.length);
//if the length value of the text field is blank - show error
if (val == "") {
document.getElementById("errorStyle").style.borderColor = "red";
return false
} else {
//if they are not blank remove error text
document.getElementById("errorStyle").style.borderColor = "green";
}
}
You can find a fiddle sample here:
http://jsfiddle.net/a45gn9w4/
You need to listen to the submit of your form and call the function formValidation()
Then you can actually get those elements and validate if it is correct or not.
This is the html:
<form id="surveyForm" method="post" action="some_url_to_post">
<label id="">Favourite movie?<span id="error" class="noErrorHappen">*</span></label>
<input type="text" id="favMov" name="favMov">
<br/>
<input type="submit" id="validator" value="Submit">
</form>
This is the js:
var error = document.getElementById("error");
var form = document.forms.surveyForm,
elem = form.elements;
function formValidation() {
if(!elem.favMov.value){
alert('please input text.');
elem.favMov.focus();
error.className = "errorHappen";
return false;
} else {
error.className = "noErrorHappen";
return true;
}
}
form.onsubmit = formValidation;
This is the CSS:
.errorHappen {
display: block;
color: red;
}
.noErrorHappen {
display: none;
}
#error {
float: left;
}
Hello all: I recently stumbled upon a question about form validation, which I'm currently trying to get working. I got the code from an answer and then customized it to more what I'm needing.:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function Validate(){
if(!validateForm()){
alert("Something happened");
return false;
}
return true
}
function validateForm()
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked){return true}
}
}
return false;
}
</script>
</head>
<body>
<form name="myForm" action="http://upload.wikimedia.org/wikipedia/commons/3/30/Googlelogo.png" onsubmit="return Validate()" method="get">
<input type="checkbox" name="live" value="yesno">You are alive.
<br>
<input type="checkbox" name="type" value="person">You are a person.
<br>
<input type="checkbox" name="eyes" value="color">Your eyes have color.
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
NOTE: The image is just from a Google Image Search, and is on Wikipedia (I do not own it).
Now, when I originally entered the HTML from the answer into the Tryit Editor at W3 Schools, it would give me a "Something Happened" alert, or do nothing. (I think that's what is was supposed to do).
Still, (now that I have my own questions) it will say "something happened" if nothing is selected, but no matter how many check (over 1 checked) it will just give me the image. Basically, what I want is it to check if ALL or ONLY SOME are checked. If all are checked i want one image, and if only some, I want a different one.
I hope this isn't too confusing, and I appreciate any help :)
P.S.:Here is the question where I got the code: Original Question
Try this for the script section, it will change the form's "action" attribute (which points the form to a the desired URL upon submitting) after validating how many checkboxes are checked:
<script type="text/javascript">
function Validate(formRef){
var checkboxes = getCheckboxes(formRef);
var checkedCount = validateForm(checkboxes);
if(checkedCount == checkboxes.length){
// All are checked!
return true;
} else if(checkedCount > 0) {
// A few are checked!
formRef.setAttribute('action', 'http://upload.wikimedia.org/wikipedia/commons/thumb/2/24/Yahoo!_logo.svg/200px-Yahoo!_logo.svg.png');
return true;
} else {
alert("Something happened");
}
return true;
}
function getCheckboxes(formRef) {
var c = formRef.getElementsByTagName('input');
var checkboxes = [];
for (var i = 0; i<c.length; i++){
if (c[i].type == 'checkbox')
{
checkboxes.push(c[i]);
}
}
return checkboxes;
}
function validateForm(checkboxes) {
var checkedCount = 0;
for (var i = 0; i < checkboxes.length; i++){
if (checkboxes[i].checked){
checkedCount++;
}
}
return checkedCount;
}
</script>
The form HTML should be updated to pass "this", the reference to the form object being validated, into the Validate() function, to avoid the need to query for it again:
<form name="myForm" action="http://upload.wikimedia.org/wikipedia/commons/3/30/Googlelogo.png" onsubmit="return Validate(this)" method="get">
Try this (will alert first option if one or more but less than 3 checked, will alert second option if exactly 3 checked):
<!DOCTYPE html>
<html>
<body>
<input type="checkbox" name="live" value="yesno">You are alive.
<br>
<input type="checkbox" name="type" value="person">You are a person.
<br>
<input type="checkbox" name="eyes" value="color">Your eyes have color.
<br>
<input value="Submit" type="submit" onclick="
var count = 0;
for(var i = 0; i < document.getElementsByTagName('input').length - 1; i++)
{
if(document.getElementsByTagName('input')[i].checked)
{
count += 1;
}
}
if(count >= 1 && count < 3)
{
alert('First Option');
}else
{
if(count == 3)
{
alert('Second Option');
}
}" />
</body>
</html>
The following should get you on the right path:
function Validate() {
var checkboxes = processCheckboxes();
if (checkboxes.all.length == checkboxes.checked.length) {
alert("All are checked");
} else if (checkboxes.checked.length > 0) {
alert("Some checked");
} else {
alert("None checked");
}
return false;
}
function processCheckboxes() {
var checkboxes = document.querySelectorAll('input[type=checkbox]');
var checked = [].filter.call( checkboxes, function( el ) {
return el.checked
});
return { all: checkboxes, checked: checked };
}
You can then process the checked boxes in whatever manner you like before submitting.
See a working example here: http://jsfiddle.net/jkeyes/Zcu7d/
I need to disable the submit button when the required fields are not filled. But the script is not working. If anybody can help, thanks in advance.
Html :
<input type="submit" value="Submit" name="sub1" id="submit1">
Javascript :
<script language="JavaScript">
function form_valid() {
var u1=document.getElementById("#user1").value;
var p1=document.getElementById("#pass1").value;
var p2=document.getElementById("#pass2").value;
var s1=document.getElementById("#school1").value;
if ((u1 == null)&&(p1 != p2)&&(s1 == null))
{
document.getElementById("#submit1").disabled = true;
document.getElementById("#submit1").setAttribute("disabled","disabled");
}
else
{
document.getElementById("#submit1").disabled = false;
document.getElementById("#submit1").removeAttribute("disabled");
}
}
function form_run() {
window.setInterval(function(){form_valid();}, 1000);
}
</script>
Body tag (HTML) :
<body bgcolor="#d6ebff" onload="form_run();">
var u1=document.getElementById("#user1").value;
Dont use #, you have many times in your code
var u1=document.getElementById("user1").value;
I want to validate a form but I want to have 9 different functions to validate the form. Which validation function gets used should be determined by a slider on the screen, or rather by the value in the span "range" which is controlled by the slider)
I can validate the form fine if I'm just using one function to do so with the below:
<script>
function validateFormMethod1() {
// do my validation stuff here
}
</script>
<form method="post" action="whatevermailscript.php"name="GuestInfo" onSubmit="return validateFormMethod1();">
<input type="submit" value="Send" name="submit" />
<span>Guests</span>
<span id="range">1</span>
<input id="scaleSlider" type="range" value="1" min="1" max="9" step="1" onchange="showValue(this.value) ; showOrHide(this.value)"/>
But how can I add to this this so that if range.value==2 validateFormMethod2 would get called instead of validateFormMethod1?
Update 3:
<script>
function validateFormMethod0() {
}
function validateFormMethod1() {
window.alert("Method 1");
return false;
}
function validateFormMethod2() {
window.alert("Method 2");
return false;
}
function validateFormMethod3() {
window.alert("Method 3.");
return false;
}
function validateFormMethod4() {
window.alert("Method 4.");
return true;
}
var validationFunctions = [
validateFormMethod0,
validateFormMethod1,
validateFormMethod2,
validateFormMethod3,
validateFormMethod4
];
function validateForm() {
var range = document.getElementById("range");
validationFunctions[range.innerHTML]();
}
</script>
Still cant quite get this working as suggested but this serves my purpose:
function validateForm()
{
var range = document.getElementById("range");
if (range.innerHTML == "1")
{
// do my validation stuff for case one here
}
if (range.innerHTML == "2")
{
// do my validation stuff for case two here
}
}
Use an array of functions.
var validationFunctions = [
validateFormMethod1,
validateFormMethod2,
validateFormMethod3,
....
];
function validateForm() {
validationFunctions[range.value]();
}
I'm new to JavaScript and my form validation works but keeps jumping to validate username on submit even when its validated. Heres my code
function validate_form(form)
{
var complete=false;
if(complete)
{
clear_all();
complete = checkUsernameForLength(form.username.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkEmail(form.email.value);
}
if (complete)
{
clear_all();
complete = checkphone(form.phone.value);
}
}
function clear_all()
{
document.getElementById('usernamehint').style.visibility= 'hidden';
/*.basicform.usernamehint.style.backgroundColor='white';*/
document.getElementById("countrthint").style.visibility= 'hidden';
/*document.basicform.countrthint.style.backgroundColor='white';*/
document.getElementById("subhint").style.visibility= 'hidden';
/*document.basicform.subject.style.backgroundColor='white';*/
document.getElementById("phonehint").style.visibility= 'hidden';
/*document.basicform.phone.style.backgroundColor='white';*/
document.getElementById("emailhint").style.visibility= 'hidden';
/*document.basicform.email.style.backgroundColor='white';*/
}
heres the functions
function checkUsernameForLength(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 2) {
fieldset.className = "welldone";
return true;
}
else
{
fieldset.className = "";
return false;
}
}
function checkEmail(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt))
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkphone(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if ( /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/.test(txt)) {
fieldset.className = "welldone";
}
else
{
fieldset.className = "FAILS";
}
}
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
window.onload = func;
} else {
window.onload = function()
{
oldonload();
func();
}
}
}
function prepareInputsForHints()
{
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++)
{
inputs[i].onfocus = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
}
inputs[i].onblur = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}
addLoadEvent(prepareInputsForHints);
and heres my form
<form form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" >
<fieldset>
<label for="username">Name:</label>
<input type="text" id="username" onkeyup="checkUsernameForLength(this);" />
<span class="hint" id="usernamehint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="country">Country:</label>
<input type="text" id="country" onkeyup="checkaddress(this);" />
<span class="hint" id="countryhint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="Subject">Subject:</label>
<input type="text" id="subject" onkeyup="checkaddress(this);" />
<span class="hint" id="subhint">Please Indicate What Your Interest Is !</span>
</fieldset>
<fieldset>
<label for="Phone">Phone:</label>
<input type="text" id="Phone" onkeyup="checkphone(this);" />
<span class="hint" id="phonehint">This Feld Must Be Numeric Values Only !</span>
</fieldset>
<fieldset>
<label for="email">Email Address:</label>
<input type="text" id="email" onkeyup="checkEmail(this);" />
<span class="hint" id="emailhint">You can enter your real address without worry - we don't spam!</span>
</fieldset>
<input value="send" type="button" onclick="validate_form(this.form)"/>
<br /><br /> <br /><br />
</form>
Please point amateur coder in right direction Thanks
Like others said, you are trying to access the username inside a condition, where the condition is always false. You set complete=false on start and right after that you try to see if that is true.
By the way, clear_all() may not have the behavior you want before the first validation. It will hide every input in the screen, so if there is anything else wrong, you won't be able to see that. I should go for hiding at the end (or at the beginning like #mplungjan stated, and always depending on what you need), maybe reusing your if(complete) structure:
function validate_form(form)
{
clear_all();
var complete = checkUsernameForLength(form.username.value);
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
}
Also, and after stating the username validation works, you should return a boolean value in the other methods =)
EDIT: Also, checking the errors the others said is a high priority issue.
EDIT2: I turned to see a repeated condition. Now I deleted it. To keep using the if(complete) that way, you should also do these changes:
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
return true; // <-- this change
}
else
{
fieldset.className = "";
return false; // <-- and this change
}
}
Also, change the other methods to return true and false when you need.
Don't panic.
Everyone has to start somewhere and it can be very frustrating when you're only just learning the ropes.
In answering this question, we need to look not only at your JavaScript, but at the HTML as well.
You don't have a submit input type; instead opting for a regular button. That wouldn't necessarily be a problem, except nowhere in your JavaScript are you actually submitting your form. That means every time someone clicks the "Send" button, it will fire the validate_form() function you've defined but do nothing further with it. Let's make a couple of changes:
Replace your button with a submit input:
<input value="send" type="submit" />
Next, add the following code to your form tag so that we define an action to take when the user tries to submit your form:
onsubmit="validate_form(this)"
So your whole form tag now looks like this:
<form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" onsubmit="return validate_form(this)">
Notice I removed an extra "form" from that element.
Ok, next we want to handle what happens when the form is ready to be validated.
function validate_form(form)
{
// ...we can step through each item by name and validate its value.
var username = checkUsernameForLength(form["username"].value);
var email = checkaddress(form["country"].value);
// ...and so on.
return (username && email && {my other return values});
}
Each method you call (e.g. CheckUsernameForLength) should return either true or false, depending on whether the input is valid or not.
Our last return is probably a little inelegant, but is a verbose example of a way to aggregate our returned values and see if there are any "failed" values in there. If all your methods returned true, that last return will evaluate to true. Otherwise (obviously) it will return false.
The submission of the form will depend on whatever value is returned from your validate_form() function.
Please start with this ( http://jsfiddle.net/4aynr/4/ )
function validate_form(form)
{
var complete=false;
clear_all();
complete = checkUsernameForLength(form.username); // pass the FIELD here
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
if (!complete) alert('something went wrong')
return complete;
}
and change
<form form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform" >
to
<form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform"
onSubmit="return validate_form(this)">
and change
<input value="send" type="button" onclick="validate_form(this.form)"/>
to
<input value="send" type="submit" />