September 9, 2013

Only one if/else statement executing

Clarisse’s Question:

I have two if/else statements comparing the same variable, with in one function. I do not desire, nor see a reason to nest the statements.

function checkUser() {
  var user = document.getElementById('usern').value;
  var element = document.getElementById('labelUser');

  if (user.length < 3 || user.length > 15) {
    element.innerHTML = "Invalid length.";
    element.style.color = "red";

  } 
  else {
    element.innerHTML = '<img src="http://www.zrfunding.com/wp-content/uploads/2013/05/CheckMarkSmallGreen.jpg" alt="Valid" height="35" width="30"/>';  
  }   

  if (user.match(/[<>!@#$%^&*,]+/i)){ 
    element.innerHTML = "Invalid characters.";
    element.style.color = "red";

  }   
  else {
    element.innerHTML = '<img src="http://www.zrfunding.com/wp-content/uploads/2013/05/CheckMarkSmallGreen.jpg" alt="Valid" height="35" width="30"/>';  
  }     

}

How could this code be improved?

function checkUser() {
  var user = document.getElementById('usern').value;
  var element = document.getElementById('labelUser');

  if (user.length < 3 || user.length > 15) {
    element.innerHTML = "Invalid length.";
    element.style.color = "red";

  } 
  else if (user.match(/[<>!@#$%^&*,]+/i)){ 
    element.innerHTML = "Invalid characters.";
    element.style.color = "red";

  }   
  else {
    element.innerHTML = '<img src="http://www.zrfunding.com/wp-content/uploads/2013/05/CheckMarkSmallGreen.jpg" alt="Valid" height="35" width="30"/>';  
  }     
}

You can minimize the code like this:

  var gotoElse = false;
  if (user.length < 3 || user.length > 15) {
    element.innerHTML = "Invalid length.";
    element.style.color = "red";

  } 
  else gotoElse = true; 

  if (user.match(/[<>!@#$%^&*,]+/i)){ 
    element.innerHTML = "Invalid characters.";
    element.style.color = "red";

  }   
  else gotoElse = true;

  if(gotoElse) {
    element.innerHTML = '<img src="http://www.zrfunding.com/wp-content/uploads/2013/05/CheckMarkSmallGreen.jpg" alt="Valid" height="35" width="30"/>';  
  }     
May 30, 2013

Javascript not checking whether a checkbox was selected or not

User2437473’s Question:

I’m trying to build a quiz with multiple choice questions, one of which has multiple correct answers. So I’m trying to check which checkboxes in my questions have been selected by a student in order to give the right feedback. my code is:

for(var i = 0; i< input1.length; i++)
    {
        if(input1[0].checked && input1[1].checked)
        {
        submit_answer.onclick = showFeedback1; 
        }
        else
        {
        submit_answer.onclick = false1; 
        }
    }

It never takes the first if, even if I select those two only. No matter what I put in the if statement, it only takes the else.

and this is just a part of my .js

var quiz = document.getElementById('quiz');

var questions = quiz.getElementsByTagName('p');

input1 = questions[0].getElementsByTagName('input');

var submit_answer = document.getElementById('submit_answers'); // this is the submit button

I cannot make proper assumption of what you are trying to do.

FIRST PROBLEM

Your for loop is incrementing on 1, so on the each next iteration it is comparing using same previously used value.

SECOND PROBLEM

Your structure is horrible, your script fetches up all the input elements inside every p. You should properly organize your element in groups and then match whether or not they are checked.

September 12, 2012

Access String variable from one if statement in another

Question by user185812

I am new to java coming from C#.

If I have a string that gets set in an “if-statement” is there a way to carry that string’s value to other if statements?

E.g. I set the String hi to carry the text “hello” in an if statement, but now have a completely separate if statement, and would like to use the value set to the String hi in the previous if statement.

My issue is that the veriable can’t be set until certain things in the if statement happen.

if(add.equals(temp)) {
    System.out.println ("What is the first number?");
    numberone = listen.nextDouble ();
    System.out.println ("What is the second number?");
    numbertwo = listen.nextDouble ();
    numberthree = numberone + numbertwo;
    previousproblem = numberthree;
    System.out.println ("The answer is " + numberthree);
}

So later on, in another if statement I, need to reference previousproblem, but it can’t be set until this if statement, as numberthree isn’t set until this statement.

Answer by dasblinkenlight

Java is identical to C# in this respect, all you need to do is declaring the variable outside both if statements, and set its initial value:

String s = null;
if (someCondition) {
    s = "hello";
}
if (anotherCondition) {
    System.out.println("s is "+s);
}

Answer by Starx

Define the string, before you start you if and else sequence.

String str1,str2;
if(true) {
   // ... true part
   str1 = "hello";
} else { 
   // ... false part
}

Now in another If

if(true) {
    str2 = str1; //assign the value of str1 to str2 demonstrating the use str1 in another if
}
May 2, 2012

make an ifnot statement and if statement in one line

Question by sven30

I’m trying to make an if statement with 2 conditions. One that checks if one variable is NOT present & does NOT matches the word “good2go” and the other that checks to make sure “body” variable is present. I’m trying to trip the error message here. Here is what I have and what I’ve tried, and none of it seems to work.

if (stripos($_POST['check'], 'good2go') == FALSE && $_POST['body']) {        
                $error = true; } 

if (!$_POST['check'] == 'good2go' && $_POST['body']) {  
                $error = true; }

if (!stripos($_POST['check'], 'good2go') && $_POST['body']) {   
                $error = true; }

if ((!stripos($_POST['check'], 'good2go')) && $_POST['body']) { 
                $error = true; }

How do I get this to work?

here’s the entire code of contact_us.php this has the validation code and the email code.

    $error = false;
  if (isset($_GET['action']) && ($_GET['action'] == 'send')) {

          // Winnie the pooh check
         //$t = tep_db_prepare_input($_POST['verify']);
         if (!isset($_POST['check']) && !$_POST['check']=='good2go' && isset($_POST['body'])) {
                $error = true;              
        } else  {  // Winnie the pooh Check

    $name = tep_db_prepare_input($_POST['name']);
    $email_address = tep_db_prepare_input($_POST['email']);


//IP recorder start
$ipaddress = $_SERVER["REMOTE_ADDR"];
$ip = "nnIP: " . $ipaddress;
$content = "nnName: ".$name."nnComments: ".$_POST['enquiry'];
$product = tep_db_prepare_input($_POST['product']);
    if ($product) { 
$product_text = "nnProduct Interest: ".$product; }
$content_ip = $content . $product_text. $ip;
$enquiry = tep_db_prepare_input($content_ip);
//IP recorder end


        }
 // BOF: Remove blank emails
// if (tep_validate_email($email_address)) {
// tep_mail(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, EMAIL_SUBJECT, $enquiry, $name, $email_address);
// tep_redirect(tep_href_link(FILENAME_CONTACT_US, 'action=success'));
// } else {
// $error = true;
// $messageStack->add('contact', ENTRY_EMAIL_ADDRESS_CHECK_ERROR);
    if (! tep_validate_email($email_address)) {
        $error = true;
        $messageStack->add('contact', ENTRY_EMAIL_ADDRESS_CHECK_ERROR);
    }
    if ($enquiry == '') {
        $error = true;
        $messageStack->add('contact', ENTRY_EMAIL_CONTENT_CHECK_ERROR);
    }
    if ($error == false) {      
      tep_mail(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, EMAIL_SUBJECT, $enquiry, $name, $email_address);

      tep_redirect(tep_href_link(FILENAME_CONTACT_US, 'action=success'));
// EOF: Remove blank emails
    }
  }

Answer by dweiss

Solution to your updated problem:

if (!isset($_POST['check']) || !$_POST['check']=='good2go' || !isset($_POST['body'])) {
                $error = true;              
} 

The reason for the pipes vs ampersands is that you want to throw an error if ANY of the fields has issue. Also, you want to check if body is NOT set vs IS set. Glad this worked out for you!

Answer by Starx

No need for all those unneeded functions. What you are trying to achieve is:

if (isset($_POST['check']) && $_POST['check']=='good2go' && !isset($_POST['body']) {
   // your code 
}

However, As per the title of the question: Use a ternary statement. Syntax is as such

$var = <condition> ? <true> : <false>;
April 29, 2012

My if statement ALWAYS returns true, no matter what

Question by user1364363

This just is’t making sense to me at all.

This is my code:

boolean that = false;
        if (that == true);
        {
            System.out.println("That is " + that);
        }

And yet it will print the line even though my output is

That is false

I’m doing this in java and I’m using Eclipse galileo, so each time I compile/run my program it saves it so the compiler should be getting updated version of my program.
What’s going on?

Answer by Peter Lawrey

A common mistake. Remove the ; at the end of the if statement.

BTW I always write the following if I use brackets and I use the code formatter of the IDE.

    if (that == true) {
        System.out.println("That is " + that);
    }

This means if you have a mis-placed ; or { it can be more obvious.

Answer by Starx

if (that == true);
              // ^ The extra colon you dont need
April 18, 2012

Weird issue with a php if statement

Question by FunkyMonk91

I want to use this page to determine if the user has either updated a newsletter or created a new one. It connects to the database no problem and will update, but I can not get it to insert a fresh one as it gives me this error:

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ” at line 1

If I remove the if statement and just force it to insert a new record it will work with no issues.

Any advice would be greatly appreciated, thank you.

<?php
$server = "localhost";
$username = "user";
$password = "****";
$database = "test";

$con = mysql_connect($server, $username, $password);

$title = $_POST["title"];
$body = $_POST["body"];
$transaction = "Record Added";

if (!$con)
{
    die('Could not connect: ' . mysql_error());
}

mysql_select_db($database, $con);

if(isset($_POST["id"]))
{
    $sql = "INSERT INTO newsletter (date, title, body)
    VALUES('1990-12-12', '$title', '$body')";       
}
else
{
    $id = $_POST["id"];
    $transaction = "Record Updated";
    $sql = "UPDATE newsletter SET title='".$title."', body='".$body."' WHERE newsletterId =".$id;   
}

if (!mysql_query($sql,$con))
{
    die('Error: ' . mysql_error());
}

echo $transaction;

mysql_close($con);
?>

Answer by jeroen

Your logic seems flawed, if an ID is posted you try to insert and when no ID is posted you try to update:

if(isset($_POST["id"]))
{
    $id = $_POST["id"];
    $transaction = "Record Updated";
    $sql = "UPDATE newsletter SET title='".$title."', body='".$body."' WHERE newsletterId =".$id;        
}
else
{
    $sql = "INSERT INTO newsletter (date, title, body)
    VALUES('1990-12-12', '$title', '$body')";   
}

That is where your error comes from, your $id is empty.

Apart from that you should look into sql injection. Switching to prepared statements is the best way to go.

Answer by Starx

Quotes your query properly

$sql = "UPDATE newsletter SET title='".$title."', body='".$body."' WHERE newsletterId ='$id'";
April 7, 2012

php comparing 2 co-ords

Question by user1022585

I don’t know why, but this doesn’t seem to work.

Basically I want this to be true if the player1 ($playerX, $playerY) is within one square from player2 ($rs[x], $rs[y])

if (($rs[x] > $playerX-2 or $rs[x] < $playerX+2) && ($rs[y] > $playerY-2 or $rs[y] < $playerY+2)) {
    // code

Any idea what I’m doing wrong?

Answer by Starx

Your conditions end up on true due to the OR operator

if (($rs[x] > $playerX-2 && $rs[x] < $playerX+2) && ($rs[y] > $playerY-2 && $rs[y] < $playerY+2)) {
   //your code
}
April 5, 2012

mysql_fetch_assoc inside if then statement

Question by BBuchanan

So, I’m still new with the php coding, still learning, etc. So, if this has been asked before I’m sorry. I’m writing this off the top of my head, so any mistakes, again, sorry.

I want to pull info from the database and if it’s a number then display text instead. So, I thought something like this would work (I have to check 1 – 12 with a specific word):

 if(mysql_fetch_assoc($result) == 1){
 echo "student";
 }else
  "generic error";

or since I have to do 1 – 12

if($row_members['ulevel'] == 1){
echo "Student";
}else
"generic error";

When users register, they are assigned a number as part of the insert, so there shouldn’t be any error.
So I guess it’s a multi-part question. How do I create a statement to check the ulvel and print it as text. 1 being a observer and 12 being the admin.

Answer by Starx

mysql_fetch_assoc() does not return integer value, it returns associative array of strings.

To check the status, you can simply put expression inside the if expression.

$row = mysql_fetch_assoc($result);
if($row['ulevel'] == 1){
 echo "student";
} else
  "generic error";

If you are checking among multiple rows

while($row = mysql_fetch_assoc($result)) {
    if($row['ulevel'] == 1){
     echo "student";
    } else
      "generic error";
}
April 3, 2012

if/else statement in a function: using onclick as a switch

Question by Aurora Schmidt

I have looked for solutions to this on google for what seems like an eternity, but I can’t seem to formulate my search correctly, or nobody has posted the code I’m looking for earlier.

I am currently trying to make a function that will modify one or several margins of a div element. I want to use an if/else statement within the function, so that the onclick event will switch between the two conditions. This is what I have been working on so far;

function facebookToggle()
{
    if($('#facebooktab').style.margin-left == "-250px";)
    {
        document.getElementById("facebooktab").style.marginLeft="0px";
    }
    else
    {
        document.getElementById("facebooktab").style.marginLeft="-250px";
    }
}

I have tried twisting it around a little, like switching between “marginLeft” and “margin-left”, to see if I was just using the wrong terms.. I’m starting to wonder if it might not be possible to combine jQuery and regular javascript? I don’t know.. It’s all just guesses on my part at this point.

Anyway, I have a div, which is now positioned (fixed) so almost all of it is hidden outside the borders of the browser. I want the margin to change onclick so that it will be fully shown on the page. And when it is shown, I want to be able to hide it again by clicking it.

I might be approaching this in the wrong way, but I really hope someone can help me out, or even tell me another way to get the same results. Thank you for any help you can give me.

You can see it in action at: http://www.torucon.no/test/

(EDIT: By the way, I am a complete javascript novice, I have no experience with javascript prior to this experiment. Please don’t be too harsh, as I am aware I probably made some really stupid mistakes in this short code.)

Fixed problem:

function facebookToggle() {
var fb = $('#facebooktab'); // save reference to element
if( fb.css('margin-left') === '-250px' ) {
    fb.css('margin-left', '0px');
} else {
    fb.css('margin-left', '-250px');
}
}

Answer by paislee

A jQuery object doesn’t have a property called style, so

if($('#facebooktab').style.margin-left == "-250px";)
//                   also remove this semi-colon! ^

is going to throw an error. Some options for accessing CSS properties are (1)

document.getElementById("facebooktab").style.marginLeft;

which you have correctly used, or (2)

$('#facebooktab').css('margin-left');

Consider being consistent and using the same approach for all three cases. You can assign css properties with jQuery like

$('#facebooktab').css('margin-left', '-250px');

With these things in mind, here’s a suggested rewrite:

function facebookToggle() {
    var fb = $('#facebooktab'); // save reference to element
    if( fb.css('margin-left') === '-250px' ) {
        fb.css('margin-left', '0px');
    } else {
        fb.css('margin-left', '-250px');
    }
}

and here’s another that uses a predefined CSS class:

#facebooktab {
    margin-left: -250px; /** default state */
}

.no-left-margin {
    margin-left: 0px;
}
function facebookToggle() {
    $('#facebooktab').toggleClass('no-left-margin');
}

Answer by Starx

Since you are mixing jQuery with javascript, you got mixed up. Apart from what paislee’s advice. you are do this too.

if($('#facebooktab')[0].style.margin-left == "-250px";){
    document.getElementById("facebooktab").style.marginLeft="0px";
}
else    {
    var fb = document.getElementById("facebooktab");
    fb.style.marginLeft="-250px";
}
...

Please fill the form - I will response as fast as I can!