What is wrong with this form validation? - javascript

Basically, what I am trying to do is alert the same message if one of the seven text boxes in my form is empty. I have been playing around with it a lot, but now I am starting to feel exasperated; help! Sometimes I get a function validepiste() is not defined error and sometimes I don't get an error, but there is an alert even if all the boxes have something in them. I think the error might be due to an incorrect use of the || (or) operator, or the length bit. Here is the function (which is within the head tags):
<script type="text/javascript">
function validatepiste()
{
// all form fields must be filled in
var a= document.piste.nom.length;
var b= document.piste.email.length;
var c= document.piste.numtel.length;
var d= document.piste.adresse.length;
var e= document.piste.ville.length;
var f= document.piste.length;
var g= document.piste.travaux.length;
if (a||b||c||d||e||f||g==0){
alert("Vous devez remplir toutes les cases.");
return false;
}
return true
}
</script>
And the call to that function which is in the html:
<input type="submit" name="Submit" value="Envoyer" onClick="return validatepiste()"/>
Thank you!

There are two issues with your code that I can see.
First Problem
It appears you're trying to access a length property directly on a form element (which doesn't exist). What you really want to do is access the length of a form value. So instead of this:
var a= document.piste.nom.length;
Do this:
var a= document.piste.nom.value.length;
I didn't see this at first but #Napster mentioned it in his answer. So thank him.
Second Problem
You're if statement has some bad logic. Try the following instead.
if (a==0||b==0||c==0||d==0||e==0||f==0||g==0) { ... }
Your original expression was asking the following...
If a is truthy,
or b is truthy,
or c is truthy,
or d is truthy,
or e is truthy,
or f is truthy,
or g is equal to 0
then show the alert.
The only scenario which would not have triggered the alert using your existing code would be if all the fields were blank except for g.
You can read an article about what truthy means if you like.

You should test each variable's value independently, i.e.:
if (a==0||b==0||c==0||e==0||f==0||g==0)

Your code is fine. Only you have to add a single thing between where the variable is defined.
Your code:
var a= document.piste.nom.length;
var b= document.piste.email.length;
var c= document.piste.numtel.length;
Modify it by
var a= document.piste.nom.value.length;
var b= document.piste.email.value.length;
var c= document.piste.numtel.value.length;
same for all the variable, add value in between them. And your code will run.

First you are not using your || operator correctly. it is only doing comparison of g==0. You are getting always a message because browser takes if(a) as a has some value. So do comparison differently for each varriable like this
if (a==0||b==0||c==0||d==0||e==0||f==0||g==0){
and second use else condition to return true. It always return true because it is not having else condition. return true always executes. and put semicolon after return true;

I think its enough if u give
onsubmit="validatepiste()"
return is not required.

Firstly try:
if (a||b||c||d||e||f||g==0){
alert("Vous devez remplir toutes les cases.");
return false;
}
else{
return true;
}
secondly try
<input type="submit" name="Submit"
value="Envoyer" onclick="validatepiste()"/>
Thirdly:
var a= document.getElementByID('nom').length;
assuming your form fields have IDs as well as names

Related

JavaScript issue on checking if both numeric values exists

Hopefully I get this format right. I know this is a newbie question and probably pretty obvious but I am confused on how to check these fields. I have two input fields on a JSP file:
<input id="CMDScheduleNumber" type="number" class="textsmall" maxlength="5"
onKeyPress="return numbersonly(this, event)"/>
<input id="CMDContractYear" type="number" class="textsmall" maxlength="4"
onKeyPress="return numbersonly(this, event)"/>
I have a function in a script called "searchEFT" that is checking if either the schedule number or contract year is populated then both must be populated.
<script type="text/javascript">
//function for onchange
$(document).ready(function () {
$("#searchEFT").click(function () {
var Cmd_Sched_Number = document.getElementById("CMDScheduleNumber");
var Cmd_Contract_Year = document.getElementById("CMDContractYear");
var Cmd_Status = document.getElementById("CMDSchedStatus");
var Cmd_Creation_Date = ocument.getElementById("CMDCreationDate");
if (Cmd_Sched_Number == "") {
If(Cmd_Contract_Year !== "")
alert("Schedule Number and EFT Contract Year must be both populated");
return;
}
else if (Cmd_Sched_Number == "") {
alert("Schedule Number and EFT Contract year must be both populated");
return;
}
When I tried to do a debugger if the Cmd_Sched_Number field the value is shown as "" but the valueasnumber is shown as 'NaN'. So when I do a check, should I check it was "" or check it as numeric with isNaN and/or IsNull?
Thanks for the help
var Cmd_Sched_Number = document.getElementById("CMDScheduleNumber");
Gets the Element.
Use .value to get value from the Element
Something like:
var Cmd_Sched_Number = document.getElementById("CMDScheduleNumber").value;
Also, since you have jQuery already, consider using it.
Like:
var Cmd_Sched_Number = $("CMDScheduleNumber").val();
Custom code validations are really a mess. How many conditions you can check? There are a lot of open source libraries and they do the job pretty much well.
I would recommend you to use validate.js. Its very simple and easy to use. It sets the rules on the fields and validate according to them.
Probably you will have to do little more efforts right now to shift your code, but it will be very easy then.
As Aragorn correctly pointed out, make sure you're getting the values, not the Jquery objects or DOM elements.
function isPopulated(val) {
return !(val === '' || isNaN(val));
}
//and then in your click event handler...:
if((isPopulated(Cmd_Sched_Number) || isPopulated(Cmd_Contract_Year)) && !(isPopulated(Cmd_Sched_Number) && isPopulated(Cmd_Contract_Year))) {
//Handle the case where one is populated and the other isn't, assuming you want to treat any non-numbers as not populated.
}
This is if you want a common block for any scenario of one populated and the other not, it will be evaluated like an XOR.
The reason my isPopulated function checks for both an empty string and isNaN is that isNaN('') will evaluated false.
If you don't care whether the entered value is actually numeric or not, then you would maybe want to check value.length > 0, for example.

Slicing a string from a textbox

I am trying to take a string entered by user from a textbox. Check the length of that string and if the string is over a given number perform the slice operation on it.
Here's what I came up with but my code does nothing. Checked console, no errors given.
html:
<form id="slice">
Enter a pharse:<input type="text" id="text_box_2"><br>
<input type="button" value="slice" onclick="Slice()">
Result: <input type="text" id="slice_result"><br>
</form>
Javascript function:
function Slice(){
var UserString = document.getElementById("text_box_2").value;
var UserStringValue = UserString.length;
var Result = Userstring.slice(1,6);
if (UserStringValue > 6){
document.getElementById("Slice_result").value = Result;
}
else{
alert("Please enter a longer phrase.")
}
}
what or where did I go wrong?
Be mindful of case-sensitivity.
This:
var Result = Userstring.slice(1,6);
Should be using UserString (capital "S") as defined earlier in your code.
Next, the input ID should be all lowercase, slice_result, to match to HTML, but your code uses different casing:
document.getElementById("Slice_result")
Here's a working JSBin with these fixes.
EDIT: As JaromandaX mentioned in the comments, if you want to take the first 6 characters you should use slice(0, 6).
from cursory reading of your code. it seems caused by this line
var Result = Userstring.slice(1,6);
and also this one
document.getElementById("Slice_result").value = Result
it should be
var Result = UserString.slice(1,6);
and
document.getElementById("slice_result").value = Result
Usually use of the following
var Value = $('#input_id').val();
will pull the requested information for you.
You can also set up arguments for your slice function and pass in the value when you run onclick();
I'd also note that slice() is a current js function, though your implentation with the capital 'S' is some what different, it may be better practice to change that name a bit.

Issue with an infinite loop?

I'm having some issues with an accidental infinite loop. I've just been starting with javascript, and so I've been trying to make a simple game as practice. I keep getting an infinite loop, and I can't tell why. I'm fairly sure it's not a syntax error, since the console isn't telling me about any. Here's the code where the problems are happening:
HTML:
<input id="lemonadePrice" class="buytextbox" placeholder="Lemonade price">
<input class="submit" onclick="begin();" type="submit" value="Begin!">
JavaScript:
while (isNaN(lemonadePrice)) {
document.getElementById("introduction").innerHTML="Uh-oh! Your lemonade price is not a
number!Please remove any words or symbols like '$'.";
lemonadePrice = document.getElementById("lemonadePrice");
}
Here's a link to the full code: jsfiddle
This might be because of your while() loop. What might be happening is that the while loop goes on infinitely while this isNAN(lemonadePrice) returns true, and this is what happens in your case, given that you say it runs infinitely.
You can try using an if(). Since .getElementById of "lemonadePrice" will not be returning a number, the isNAN() would be evaluating to true all the time. isNAN() simply means "is not a number". If you think for a second, you know where the bug is.
I think you are looking to get the value of "lemonadePrice", so instead of just getting the element, you should also consider pulling in the value that lies inside it. I do not see this in your code but it would simply be this DOM: var value = document.getElementById(id).value;
I think you want an if instead of while
The definition while taken from wikipedia
In most computer programming languages, a while loop is a control flow
statement that allows code to be executed repeatedly based on a given
boolean condition. The while loop can be thought of as a repeating if
statement.
It means while loop will repeat under condition that inside the brackets. In this case, what you need is a conditional statement (if())
If will be executed only once. While will be executed repeatedly until the condition is false. In your case, the condition will be always true. That is why you ended up in infinite loop.
See code below
if (isNaN(lemonadePrice)) {
document.getElementById("introduction").innerHTML="Uh-oh! Your lemonade price is not a
number!Please remove any words or symbols like '$'.";
lemonadePrice = document.getElementById("lemonadePrice");
}
If we assume begin() is basically this:
function begin(){
var lemonadePrice = document.getElementById("lemonadePrice");
while (isNaN(lemonadePrice)) {
document.getElementById("introduction").innerHTML="Uh-oh! Your lemonade price is not a number!Please remove any words or symbols like '$'.";
lemonadePrice = document.getElementById("lemonadePrice");
}
}
then your loop will never have a chance to exit, since lemonadePrice is always set to the "value" of the lemonadePrice DOM element; that means lemonadePrice will always be NaN, so the loop is infinite. Like others have already mentioned, you need to use an if() statment instead of a loop, and remove the last line. You also want to look at the value of the element:
function begin(){
var lemonadePrice = document.getElementById("lemonadePrice").value;
if(isNaN(lemonadePrice)) {
document.getElementById("introduction").innerHTML="Uh-oh! Your lemonade price is not a number!Please remove any words or symbols like '$'.";
}
}
You better use onsubmit and prevent form submit if not valid.
Its also better to use regular expression to check if its valid float number.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="yourfile.php" method="post" onsubmit="validate();">
<input id="lemonadePrice" class="buytextbox" placeholder="Lemonade price" /> <span id="lemonade_error"></span>
<br>
<input class="submit" type="submit" value="Begin!" />
</form>
<script type='text/javascript'>//<![CDATA[
function validate() {
var lemonade_price = document.getElementById("lemonadePrice").value;
if (lemonade_price.match(/\d+\.*\d*/i)){
document.getElementById("lemonade_error").innerHTML = "Not valid.";
if (event.preventDefault){
event.preventDefault();
} else {
event.returnValue = false; // for IE as dont support preventDefault;
}
return false;
}
return true;
}
//]]>
</script>
</body>
</html>
Code here : http://jsfiddle.net/Pxuey/5/

Javascript Confirm with action?

wording this question was hard, but here i go. ok, i am using code from this site:
http://www.switchonthecode.com/tutorials/javascript-tutorial-getting-user-input-with-prompt-and-confirm
<script type="text/javascript">
function confirmInput()
{
var ans = confirm("Install a virus and delete all your files?");
alert(ans ? document.getElementById('level').value = "0";
: "If no, do nothing");
}
</script>
<input type="button" onclick="confirmInput()" value="Show me the Question!" />
I have even tried to replace the Text for the answer with the actions, but i get nothing.
How do i add a action to the answer, so when it is yes, i do something, and when no i do not.
I think this is what you are looking for:
function confirmInput()
{
if(confirm("Install a virus and delete all your files?"))
document.getElementById('level').value = "0";
}
there is a syntax error in your code here:
alert(ans ? document.getElementById('level').value = "0"; // this semicolon is invalid
: "If no, do nothing");
It executes till this semicolon and that terminates. Check your console, there should be an error message.
Another thing is that ?: operator can only return a value. It shouldn't contain operations, only values or function, which returns the value.

If statement condition is met, but contents not executed?

I've got an two if() statements, for which the conditions are both met with the default values in the <select> and <input> form fields I've tested this by assigning the values to a variable and writing the variable. (0 and Url).
However, it seems that neither if() statement's contents execute properly.
Here's a link to my JSFiddle: http://jsfiddle.net/cfRAk/2/
Any edits/answers as to why this is happening would be greatly appreciated!
Change this line:
var geo_select_val = $('select[name=g_country\\[1\\]]').val();
To this:
var geo_select_val = parseInt($('select[name=g_country\\[1\\]]').val());
The thing is geo_select_val is actually "0" and not 0. Converting a string to boolean will only result in false if string is empty. "0" is not empty, so it was being evaluated as true. Since you are going !geo_select_val, it never goes in.
Caveat: this fix will only work if you make sure all values are numbers. If that's not the case, check for equality with "0"
Here's the code you're asking about:
$('#post-form').click( function() {
var geo_select_val = $('select[name=g_country\\[1\\]]').val();
if(!geo_select_val) {
var geo_url_val = $('input[name=g_url\\[1\\]]').val();
if(geo_url_val != "http://google.com") {
$('#notification').html("You need to enter a valid url");
}
}
});
When I set a breakpoint in this click function and then click on the Post Form div, geo_select_val comes back as "0" which means that if(!geo_select_val) will fail because geo_select_val does have a value so the first if condition will never be executed.
Perhaps you want the first if condition to be:
if (geo_select_val != "0") {
which will tell you if some other value besides the default has been selected (assuming you add other options to that select tag with different values).

Categories