Javascript only checks one field - javascript

Ok so I've been stumped on this one for days and its frustrating me. (Will frustrate me even more if it's something simple I'm overlooking).
I have a form generated in PHP which I want to verify that certain pieces are filled out. I do this via a JavaScript check when the user clicks the submit button.The JavaScript code is below:
<script language="JavaScript">
function checkFields()
{
if (document.getElementById('ldescription').value == '' || document.getElementById('uname').value == ''
|| document.getElementById('sdescription').value == '' || document.getElementById('email').value == ''
|| document.getElementById('platf').value == "Select Group" || document.getElementByID('cate').value == "Select Category" )
{
alert("Please fill out all of the starred (*) items" );
return false;
}
}
</script>
For some reason though this only checks the ldescription field. If that field has text but all the others are empty it carries on like everything was filled out. Also if I change the order of my checks and ldescription is anywhere but the first check, it will do no check whatsoever even when all the fields are empty.
Any ideas?
EDIT:
Got it fixed. Along with the suggestion I marked as correct the document.getElementById('item').value command worked with only textarea boxes but not regular text input boxes. By changing the command to document.MyForm.myTextName.value everything fell into place.

Couple of problems i noticed with your sample code.
The last getElementById call has improper casing. The final d is capitalized and it shouldn't be
Comparing the value to a string literal should be done by === not ==.
JSLint complains there are line break issues in your if statement by having the line begin with || instead of having the previous line end with ||.
The first and third items are most likely the ones causing your problem.

Inside your if condition, when you are breaking a line, make sure that the last token in the line is the OR operator ||.
Javascript does semicolon insertion, so it may be that semicolons are being inserted (automatically, invisibly, by the interpreter) in a bad place.
Try the below code
<script language="JavaScript">
function checkFields()
{
if (document.getElementById('ldescription').value === '' ||
document.getElementById('uname').value === '' ||
document.getElementById('sdescription').value === '' ||
document.getElementById('email').value === '' ||
document.getElementById('platf').value === "Select Group" ||
document.getElementById('cate').value === "Select Category")
{
alert("Please fill out all of the starred (*) items" );
return false;
}
}
</script>

Please use Javascript && operator which returns true if both the elements are true. || operator evaluates to true in case atleast one of the element is true which is what is happening in your case. You can take a look at Javascript boolean Logic

Related

Boolean and text field validation - Javascript

I have a form that posts to itself with a text field (for SMS number) and a boolean field (for SMS opt in). I can't seem to get the syntax correct for validation when the end-user goes to post the form.
If they select the bool for opt in, then the form should check the text field for the sms number and if the sms number is empty, display an error.
Here's my javascript snippet:
if (document.getElementById("smsOpt").checked = 'true' && document.getElementById("smsNum").value = ''){
error += "smsOpt";
document.getElementById("smsOpt").focus();
document.getElementById("smsOptError").style.display='block';
}
You can do something like this:
if (document.getElementById("smsOpt").checked && document.getElementById("smsNum").value.trim() == ''){
error += "smsOpt";
document.getElementById("smsOpt").focus();
document.getElementById("smsOptError").style.display='block';
}
For checkbox, the checked property is of type boolean so use of only "checked" is fine. And for the second property you can compare it with an empty string. Single = operator in JS is for assignment and not comparison.
You have to use == or === instead of = in vary conditions.
if (document.getElementById("smsOpt").checked == 'true' && document.getElementById("smsNum").value == ''){
error += "smsOpt";
document.getElementById("smsOpt").focus();
document.getElementById("smsOptError").style.display='block';
}
There is actually no need for using any equality operators in this case. You can do something like this:
if (document.getElementById("smsOpt").checked && !document.getElementById("smsNum").value){
error += "smsOpt";
document.getElementById("smsOpt").focus();
document.getElementById("smsOptError").style.display='block';
}
But if you want to use them, then do it with triple === or double equality == operators. You can check the differences between theese two here.
In JavaScript = is only for assignment, so your if-statement is setting checked=true on the input rather than checking what is it. (Or it actually sets it to true no matter what it was and then evaluates the result of setting the value which will always be true)
You need to use == or better ===
if (document.getElementById("smsOpt").checked === true && document.getElementById("smsNum").value.trim() === '') {
I added trim() also so it ignores if you just insert spaces.

How do I write a script for a IF/OR statement for multiple instances?

I'm trying to write a script rule that's like the following:
if (Field(A) == "Yes" || Field(B) == "Yes" || Field(C) == "Yes")
return "TITLE"
else
return ""
I have it functioning if I'm only doing "if A OR B", but does not work if I add another field into the mix.
What I'm trying to accomplish is offering a list of items that a user has to choose "yes" or "no" for. If ANY of the three is a "yes", I need the title to show up. So if NONE of them is a "yes", then the title will not show up.
Any suggestions? I've searched around multiple sites and cannot find anything that works.
That code should work, so if a given field is not working, then the value for that field is probably not what you're expecting it to be. I suggest using console.log(myFirstVar, mySecondVar, myThirdVar) immediately before the if statement to see what your values are before they hit the if.
Also, it's good practice to use === instead of ==. They usually resolve in the same way but == will return a match in many cases that === does not. Specifically == treats all truthy and falsey values as equal, such that if you're doing an if (myVar == false) check, you'll get true if myVar is 0, false, undefined, etc.
Your code just work fine you can Play with the following Fiddle to see that what are you doing is right.
Using span for displaying the change on test.
HTML :
<span id="title"></span>
JS :
var fieldA = 'Yes';
var fieldB = 'No';
var fieldC = 'No';
if (fieldA == "Yes" || fieldB == "Yes" || fieldC == "Yes")
document.getElementById('title').innerHTML ="TITLE";
else
document.getElementById('title').innerHTML = "";

charCodeAt() working with some validations, but not some other validations

I could have sworn I validated everything properly until my teacher decided to look for every single possible combination of characters and somehow doc me for 10 points. So I went in my code and try to fix the validation but, even though this is just like the example in his lecture outline, it decides to let a1 unwantingly pass the form. I double checked the ascii char code chart using this link
and the 1 still keeps getting through. this is my code section:
else if(f1.state.value.length != 2 ||
!( (f1.state.value.charCodeAt(0)>=65 && f1.state.value.charCodeAt(0)<=90) ||
(f1.state.value.charCodeAt(1)>=97 && f1.state.value.charCodeAt(1)<=122) ))
{
alert('Please enter a state in abreviated form');
f1.state.focus();
return false;
}
why does the 1 keep getting through?
edit: also, i notice 1a works (or doesnt work), but not a1..
interesting, i took the ! out and put it around each individual parenthesese to ! and it worked.. so it was returning true if one or the other was true... then !ing it.
so it should have been :
else if(f1.state.value.length != 2 ||
( !(f1.state.value.charCodeAt(0)>=65 && f1.state.value.charCodeAt(0)<=90) ||
!(f1.state.value.charCodeAt(1)>=97 && f1.state.value.charCodeAt(1)<=122) ))
{
alert('Please enter a state in abreviated form');
f1.state.focus();
return false;
}

Simplify this If statement so it doesn't duplicate code - Javascript

I have an If statement that runs within a 'for' loop to create markers for a Google map. Basically if a tick box is not ticked it runs the code all displays all markers, but if a checkbox is ticked then it checks for a 2nd parameter and only runs the code for the items that match this condition.
The code I have below works fine, but it means I have to use the same code in both parts of the if statement. Apart from building it into a function if there a better way of structuring the If statement to achieve this?
if(!FriendlyChecked){
//Code here
} else if(FriendlyChecked && Friendly == "Yes"){
//Same code here
}
If FriendlyChecked is false, the first condition is satisfied and the code will be executed.
Thus, if the second condition is reached, FriendlyChecked must be true, so you don't need to check it at all, you only need to check that Friendly == "Yes".
if(!FriendlyChecked || Friendly == "Yes"){
// code here
}
if( !FriendlyChecked || (FriendlyChecked && Friendly == "Yes") ) {
// your code
}
!FriendlyChecked || (FriendlyChecked && Friendly == "Yes") will check for either FriendlyChecked is false (not checked)
OR FriendlyChecked is true an value of Friendly is Yes
This will solve your problem
if((!FriendlyChecked) ||((FriendlyChecked)&&(Friendly == "Yes")){
//Code here
}

javascript if condition && condition doesn't work

the AND && operator doesn't work, but when i replace it with an OR || operation it is workin, why? I just used OR || operator for testing, what i need is an && operator.
Please help. thanks
function validate() {
if ((document.form.option.value == 1) && (document.form.des.value == '')) {
alert("Please complete the form!");
return false
} else return true;
}
i also tried nested if but it doesn't work too
if(document.form.option.value==1)
{
if(document.form.des.value=='')
{
alert ("Please complete the form!");
return false
}
}
It sounds like || is what you are looking for here. The && operator is only true if both the left and right side of the && are true. In this case you appear to want to display the message if the value is 1 or empty. This is exactly what the || operator is for. It is true if either the left or right is true
If Or operator is working, means there are some javascript errors in your second part of condition. check document.form.des.value=='' (maybe just open your javascript console in Chrome/Firefox/IE8+)
its because one of the conditions specified above returns false and loop breaks. Is you use OR ,only one must be validated and returns true.. check your code for both the conditions.

Categories

Resources