May 15, 2013

jquery fade in, fade out loop

Hcx’s Question:

I want to create a loop like this,

anim = function () {
    $('.a1').fadeOut(function () {
        $('.b1').fadeIn(function () {
            $('.b1').delay(5000).fadeOut(function () {
                $('.a1').fadeIn(function () {
                    setTimeout(anim, 2000);
                });
            });
        });
    });
};

setTimeout(anim, 2000);

but after one loop .b1 is not fade in again so what could be the problem? or is there a better way to do this?

setTimeout() executes the function once, you are looking for setInterval()

March 8, 2013

Jquery Looping through elements created at runtime

Question by dev_darin

i have a list that is passed to a page and the elements are created at runtime. I would like to loop through these elements and preform some action for each element. Under is my code:
for each person that gets created from this list i would like to preform a check on that person. Can someone help me i am only getting the check happening once:

jQuery:

$(document).ready(function() {

    $("#userId").each(function(i){
        if ($("#userId").val != '') {
            alert('not null' + i);
        }
    });                 
});

JSP:

<c:forEach items="${person}" var="person">

<input= type="text" id="userId" value="${person.userid}" />
    First name:- ${person.fName} , Last Name:- ${person.lName}
</c:forEach>

Answer by Andbdrew

you cannot have multiple elements on a page with the same id attribute. try using classes instead.

try something like:

$(document).ready(function() {

   $(".userId").each(function(i){
       if ($(this).val() != '') {
           alert('not null' + i);
       }
   });
});

Another thing to note is that .val is a method, so you need to call it to get the value. Use .val() instead of .val. As you have your code now, $(selector).val is a function, so it will never be the empty string you are testing it against.

Also your JSP should be something like:

<c:forEach items="${person}" var="person">

<input= type="text" class="userId" value="${person.userid}" />
    First name:- ${person.fName} , Last Name:- ${person.lName}
</c:forEach>

Answer by Starx

Your loop will create multiple element with same ID, first change that. It is better to use class names instead.

<c:forEach items="${person}" var="person">

    <input= type="text" class="user" id="userId-${person.userid}" value="${person.userid}" />
       <!--             ^ Use Class &  ^ Id to uniquely identify the user -->
       First name:- ${person.fName} , Last Name:- ${person.lName}
</c:forEach>

Next you can use .find() to find even the dynamically generated element. But I recommend using my solutions using the class attribute.

$(".user").each(function(i) {
    if ($(this).val() != '') {
          alert('not null' + i);
    }
});
June 17, 2012

PHP loop within a loop, option selected?

Question by David

Using PHP I echo out table rows in a loop like this:

<?php
/* SQL STUFF */

  while ($row = mysql_fetch_array($select_courseelements)) {
   echo "<tr>n";
    echo "<td>".$row['scpe_name']."</td>n";
    echo "<td>".$row['scpe_days']."</td>n";
   echo "</tr>n";
  }

Now I would like to include a <select> element with 5 predefined <option> values inside a <td> running with the loop. The option values will be 1 to 5.

There is also a column inside the $row loop that holds a value of 1 to 5 ($row['scpe_grades_status']).

Each time this value is equal to the one in the <select> I want it to change it to selected='selected'.

Would this be possible?

My <select> will look something like this when it’s beeing run in the loop:

echo "<td>n";
echo "<select id='elements_grade'>n";
        echo "<option value='1'>Registrerad</option>n";
        echo "<option value='2'>Ej påbörjad</option>n";
        echo "<option value='3'>Pågående</option>n";
        echo "<option value='4'>Godkänd</option>n";
        echo "<option value='5'>Deltagit</option>n";
        echo "<option value='6'>Ej deltagit</option>n";
echo "</select>n";
echo "</td>n";

Answer by piers

$array = array('Registrerad' => 1, 'Ej påbörjad' => 2, 'Pågående' => 3, 'Godkänd' => 4, 'Deltagit' => 5, 'Ej deltagit' => 6);

foreach ($array as $key=>$value) {
    if ($value == $row['scpe_grades_status'])
        echo '<option value="'.$value.'" selected>'.$key.'</option>';
    else
        echo '<option value="'.$value.'">'.$key.'</option>';
}

Something like that?

Answer by Starx

Sure, build the values from a loop. and you can compare the values from that part.

for($i = 1; $i<=5; $i++) {
   echo "<option value='$i'";
   echo ($row['scpe_grades_status'] == $i) ? " selected='selected'": "";
   echo ">...."</option>"
}
June 4, 2012

PHP get element using a known attribute

Question by Ilya Karnaukhov

So lets say I have:

<?php
    $template = '<img src="{image}" editable="all image_all" />';
    $template .= '<div>';
    $template .= '<img src="{image}" editable="yes" />';
    $template .= '</div>';
?>

Now what I would like is to make the script go through all the elements containing the {image} src and checking to see if any of them have the

editable="all" 

attribute.

If so: get the second editable attribute e.g.

image_all

And include that into the src.

Answer by Starx

This task can be simplified with the use of a library suggested on comments, Simple HTML DOM Parser:

It is as easy as this:

$images = array(); //an array for your images with {image} in src
$html = "...";
foreach($html->find('img') as $element)
    if($element->src == '{image}') {
        //add to the collection
        $images[] = $element;
    }
    //Also you can compare for the editable attribute same way as above.
}
May 4, 2012

Foreach loop only looping once?

Question by myladeybugg

I’m having trouble with my foreach loop opening multiple files.

My foreach loop is only running once for the first item number. The foreach loop runs then goes to the “api.php” page but then stops and doesn’t go back to the foreach loop to get the next item number. How do I tell it to go through all of item numbers in my database?

Would I use cURL somehow?

Thanks

Here’s my code:

$itemnumber = array("".$result['item_number']."");

foreach ($itemnumber as $item_number) {

echo "<form method="post" action="api.php" name="ChangeSubmit" id="ChangeSubmit">";
echo "<input type="text" name="item_number" value="{$item_number}" />";

echo "<script type="text/javascript">
function myfunc () {
var frm = document.getElementById("ChangeSubmit");
frm.submit();
}
window.onload = myfunc;
</script></form>";



}

Answer by Starx

You actually have only one item in your array. SO it is looping only once.

Your code $itemnumber = array("".$result['item_number'].""); will translate to

 $itemnumber = array($result['item_number']);

Because, the double double-quotes you provided have no significance in the code too. SO, at last the array will have only one item.

April 19, 2012

$_GET with Switch Statement

Question by Mor Sela

i have alot of get values that define the page the user gonna see , for example for “profile” i will show the profile page and so on..

to find out what page to display i tried to do something like that:

switch ($_GET) {
    case 'profile':
        require_once('function/profile.php');
        break;
    case 'team':
        require_once('function/team.php');
        break;

but it shows no result..

i send the GET request like that : index.php?profile , for example..

what is the problem here and how can i can manage to do something similar that work as well. thank you in advance!

Answer by stewe

To make your example work, you could replace $_GET with key($_GET)

Answer by Starx

$_GET is a super global variable, where the data are sent as stored as array. So you have to
access it using Index

Assuming you page you are trying to include a page when the data are sent like this:

domain.com?page=product

Then you have to use switch like this

switch($_GET['page']) {
   ....
}

Note: May be I dont have to remind you how vulnerable this code towards injection.

April 6, 2012

How to count characters in array after while loop

Question by sdfgsdfg

Do u have any ideas how to count all characters in string $chars after while loop ?

$x = 0;
$b = 0;

while ($x++ < 10) {
  echo $chars = $item->zodziai[$b++];
  echo ' ';
}

echo strlen($chars);

Answer by Starx

Concatenate the characters then count them

<?php 
$x = 0; $b = 0;
$char = ''; //define a variable to collect all the chars
while ($x++ < 10) {
   $char .= $item->zodziai[$b++]; //add to the char
   echo $chars = $item->zodziai[$b++]; echo ' ';
}
echo strlen($char); //then count all the array combined
?>
April 5, 2012

While loop returning data

Question by relentless

In the code below, I’m pulling all upcoming training classes from my database. I’m checking to see if the endDate has passed and I’m also checking if the status !='2'

I want this to return the 4 most recent results. It works fine until statusdoes =2. I understand that the loop is technically running 4 times, but only displaying the results with status !='2'

How can I change this so that if status = '2' the loop will continue until it finds 4 results that meet the criteria?

<?php
$today = date("Y-m-d");
$count = 0;
$sth = $dbh->query('SELECT * from training ORDER BY startDate ASC');  
        $sth->setFetchMode(PDO::FETCH_ASSOC); 
            while($count <= 4 && $row = $sth->fetch()) { 
                if($row['endDate'] > $today && $row['status'] != '2') {?>
                    <li>
                    <img class="post_thumb" src="/images/img.jpg" alt="" />
                    <div class="post_description">
                        <small class="details">
                            <?php echo date("m/d/Y", strtotime($row['startDate'])) . ' - ' . date("m/d/Y", strtotime($row['endDate'])) ?>
                        </small>
                        <a class="post_caption" href="/register.php?course_id=<?php echo $row['courseId'] . '&id=' . $row['id'] ?>"><?php echo $row['title'] ?></a>
                    </div>
                    </li>
                <?php }
                    $count++;
                    }
                ?>  

Answer by Victor Nitu

You must put the $count++ inside the if loop, otherwise it will always get incremented.
As in:

<?php
$today = date("Y-m-d");
$count = 0;
$sth = $dbh->query('SELECT * from training ORDER BY startDate ASC');  
        $sth->setFetchMode(PDO::FETCH_ASSOC); 
            while($count <= 4 && $row = $sth->fetch()) { 
                if($row['endDate'] > $today && $row['status'] != '2') {?>
                    <li>
                    <img class="post_thumb" src="/images/img.jpg" alt="" />
                    <div class="post_description">
                        <small class="details">
                            <?php echo date("m/d/Y", strtotime($row['startDate'])) . ' - ' . date("m/d/Y", strtotime($row['endDate'])) ?>
                        </small>
                        <a class="post_caption" href="/register.php?course_id=<?php echo $row['courseId'] . '&id=' . $row['id'] ?>"><?php echo $row['title'] ?></a>
                    </div>
                    </li>
                <?php 
                $count++;
                }
            }
?>

Answer by Starx

You can break out out of the loop, if its four

while($row = $sth->fetch()) { 
        ....
        if($row['status']=='2' && $count >="4") break;
        $count++;
}
March 12, 2012

two foreach loops combined for email sending

Question by Bowser Entertainment

I am trying to take a two text areas with multiple emails, one with the “from” emails, and one with the “to” emails. Combine the emails line by line and send emails out accordingly.

Ex:

“To” list:

        mike@gmail.com

        nick@hotmail.com

        adam@yahoo.com

“From” list:

        ashley@gmail.com

        brittney@yahoo.com

        racheal@hotmail.com

I want a email sent to:

   mike@gmail.com from ashley@gmail.com

   nick@hotmail.com from brittney@yahoo.com

   adam@yahoo.com from racheal@hotmail.com

Any help would be greatly appreciated. Thanks in advanced.

Below is the script I got so far, It sends to multiple emails from one email.

 <?php
 if (isset($_POST['submit']))
 {

    // Execute this code if the submit button is pressed.
    $raw_email_account = $_POST['email_from'];
    $email = $_POST['email_to'];
    $sent = "";
    $invalid = "";

    //Separating each line to be read by foreach
    $list = explode("n",$email);

    //Rendering the separeted data from each line
    foreach($list AS $data) {
                //Separating each line to be read by foreach
            $item = explode(":",$data);
            $mail_body = '<html><body>email here</body></html>';
                $subject = "subject here";
                $headers  = "From:".$raw_email_account."rn";
                $headers .= "Content-type: text/htmlrn";
                $to = $item[0];

                $mail_result = mail($to, $subject, $mail_body, $headers);

            if ($mail_result) {
               $valid++;
            } else {
                   // write into an error log if the mail function fails
                   $invalid++;
            }
    }

}
?>
<html>
<head>
</head>
<body>
<form action="email_sender.php" method="POST">
<div align="center">From Email Accounts: <textarea name="email_from" cols="100"    rows="60"></textarea></div><br />
<div align="center">To Email Accounts: <textarea name="email_to" cols="100" rows="60">        </textarea></div><br />
<div align="center"><input type="submit" name="submit"></div>
<br>
Valids: <?php echo $valid;?>
<br>
Invalids: <?php echo $invalid;?>
</body>
</html>

Answer by Vitalmax

Add logic that provides same count of $email and $raw_email_account arrays before foreach loop.

$list = explode("n",$email);
$list2 = explode("n", $raw_email_account);

foreach($list AS $key=>$data) {
            ...
            $headers  = "From:".$list2[$key]."rn";
            ...
}

Answer by Starx

If the array is by default, the indexes will coincide. So you can do something like this.

$toList = array(..);
$fromList = array(...);

foreach($toList as $key => $value) {
    $toAddress = $value;
    $fromAddress = $fromList[$key]; 
    //..
    //.. Go on with you mail function
}
March 11, 2012

Better way of splitting and assigning many values in Javascript?

Question by Aaron

I have a for loop that cycles through the number of elements that the user has created. There are a lot of available settings in this plugin, and each element can receive it’s specific settings.

  1. User settings are entered in the following format: speed_x: “1000,500 > 1000,200 > 0,0”
    This controls the speed_x in/out for 3 separate elements. The > divides by object and the commas separate the in/out.

  2. So I can grab specific object speed_x values, I’ve split speed_x into speed_x_set (splitting by >) resulting in:

1 1000,500
2 1000,200
3 0,0`

3 Inside the loop, I grab the value by index (since it’s the object #) and split it by comma (to get speed_x_in and speed_x_out.)

for(var i=0; i<OS.numberofobjects; ++i){
   OS.speed_x_on_set[i]=speed_x_set[i].split(",")[0],
   OS.speed_x_off_set[i]=speed_x_set[i].split(",")[1],
   ...
};

Everything is assigned by object and by setting in/out correctly into the master OS settings object. T*he problem is I have many, many settings which need to be split in this fashion…* for example: delay_x_set, speed_y_set, opacity_set, etc. Their names are all based on the default setting name, with “_set” added as shown above. Hopefully this provides enough information. Thanks!

Answer by Starx

I would say to cache the split result

for(var objindex=0; objindex<OS.numberofobjects; ++objindex){
   var splits = speed_x_set[objindex].split(","); //Cache the split so its does not need to be done twice
   OS.speed_x_on_set[objindex] = splits[0];
   OS.speed_x_off_set[objindex] = splits[1];
   ...
};
...

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