...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
March 29, 2012

DISTINCT for foreach

Question by Dirk Fograust

<?php

$array = array('aaa', 'bbb', 'aaa', 'ccc', 'ddd', 'ccc', 'eee');

foreach($array as $a){
   echo $a;
}

Is possible use some like DISTINCT for foreach? I would like show each values only one, without repeat. How is the best way for this?

http://codepad.org/FZQNEBeK

Answer by tereško

Actually array_unique() gets pretty bad when you have large arrays. You would be better off with $uniques = array_flip(array_flip($array)).

Answer by Starx

Use array_unique()

$array = array('aaa', 'bbb', 'aaa', 'ccc', 'ddd', 'ccc', 'eee');
$result = array_unique($array);
print_r($result);

Demo

Read more

How can I set the title of a cluetop tooltip from ajax callback when sticky: true?

Question by leora

I am using cluetip plugin which is great. I am populating the plugin using Ajax but I can’t anywhere (in the documentation or examples) on how to set the title from an ajax callback.

Is updating the title from ajax supported in cluetip?

UPDATE NOTE:

So the suggestions given below work in the sense that they can create a title but the close button doesn’t show up in the title in this case. See image below.

enter image description here

Answer by Starx

Actually, It is pretty easy if you see from a simple angle.

First thing to note, would be that all the cluetips in the document, use only one mark-up layout to show all the tips. Every time a new cluetip is triggered, it only updates its mark-up layout and shows it.

Lets see an example of how to work around with what you are trying


I used the demo for this. So the mark-up is:

Note:I am using two cluetips to simulate a case having multiple cluetips

<a class="title" title="hello" href="http://plugins.learningjquery.com/cluetip/demo/ajax3.html" rel="http://plugins.learningjquery.com/cluetip/demo/ajax3.html">This example</a>

<a class="basic" href="http://plugins.learningjquery.com/cluetip/demo/ajax.html" rel="http://plugins.learningjquery.com/cluetip/demo/ajax.html">Basic</a>

Lets make a small change in the styles, so that it aligns correctly

.cluetip-close { float: right; margin-top: -40px; }

Now, our Script, for both the clue tips.

  var title;
  $('a.title').cluetip({
      closePosition: 'top',
      sticky: true,
      closeText: '<img src="http://plugins.learningjquery.com/cluetip/demo/cross.png" alt="close" width="16" height="16" />Close',            
      ajaxCache: false,
      ajaxSettings:  {
        success: function(data) {
            title = "Your new Title";            
            $(this).attr("title", title); //just set the title for consistency
        }
      },
      onShow : function(ct,c) {
          $(".cluetip-title").text(title); //update the title class with the title
      }
  });

  $('a.basic').cluetip(); //While definning another tip, it is NOT affected by previous one

It’s DONE

Although the fiddle might not show it. I have tested it and it works.

Read more

Combine CSS lines into one

Question by ZEDA-NL

I want to define some basic styles that I can combine. Let’s say I have a stylesheet that contains the following lines:

.whitebackground  {background-color: #ffffff}
.borderblue       {border: solid 1px #0000aa}

I’m wondering if there is there a way to include these lines into a new line? Something like:

**div.main   {.whitebackground; .borderblue}**

The result must be the same as it would be with this line:

div.main  {background-color: #ffffff; border: solid 1px #0000aa}

Answer by Starx

You are looking for SASS or LESS library.

They will allow you to include style declaration from one selector to the other.

Using LESS, you syntax will be perfectly valid and work as you want

div.main   {
   .whitebackground; 
   .borderblue;
}

But, when they are compiled, it will take the optimized form automatically.

Read more

JQuery select all options of multi-select select box on click

Question by Sachyn

This is my HTML

<select name="countries" id="countries" MULTIPLE size="8">
   <option value="UK">UK</option>
   <option value="US">US</option>
   <option value="Canada">Canada</option>
   <option value="France">France</option>
   <option value="India">India</option>
   <option value="China">China</option>
</select>
<br />
<input type="button" id="select_all" name="select_all" value="Select All">

When user click on ‘Select All’ button, I want all the options in the select box to be selected

$('#select_all').click( function() {
    // ?
});

Answer by Darin Dimitrov

Try this:

$('#select_all').click(function() {
    $('#countries option').attr('selected', 'selected');
});

And here’s a live demo.

Answer by Starx

Give selected attribute to all options like this

$('#countries option').attr('selected', 'selected');

Usage:

$('#select_all').click( function() {
    $('#countries option').attr('selected', 'selected');
});

Update

In case you are using 1.6+, better option would be to use .prop() instead of .attr()

$('#select_all').click( function() {
    $('#countries option').prop('selected', true);
});
Read more

How to develop a Jquery plugin to find the first child that match with a selector?

Question by Ivan

I’m trying to make a Jquery plugin (findFirst()) to find the first child with a given characteristics (something in the middle of the find() and children() functions. For instance, given this markup:

<div id="start">
    <div>
        <span>Hello world</span>
        <ul class="valid-result"> ... </ul>
        <ul class="valid-result">
            <li>
                <ul class="not-a-result"> ... </ul>
            </li>
        </ul>
        <div>
            <ul class="valid-result"> ... </ul>
        </div>
    </div>
</div>

If you ask for $("#start").findFirst('ul') it should return all ul lists that I have tagged with the valid-result class, but not the ul with class not-a-result. It is, this function has to find the first elements that matches with a given selector, but not the inner elements that match this selector.

This is the first time I try to code a Jquery function, and what I’ve already read doesn’t helps me too much with this. The function I have developed is this:

jQuery.fn.findFirst = function (sel) {
    return this.map(function() {
        return $(this).children().map(function() {
            if ($(this).is(sel)) {
                return $(this);
            } else {
                return $(this).findFirst(sel);
            }
        });
    });
} 

It works in the sense it tries to return the expected result, but the format it returns the result is very rare for me. I suppose the problem is something I don’t understand about Jquery. Here you have the JFiddle where I’m testing.

EDIT

The expected result after $("#start").findFirst('ul') is a set with all UL that have the class ‘valid-result’ BUT it’s not possible to use this class because it doesn’t exist in a real case (it’s just to try to explain the result).

This is not equivalent to first(), because first returns only one element!

Answer by charlietfl

You could do something like this:

var selector='ul';

var $results= $('#start '+selector).not( selector +' '+selector);

The not() method will exclude elements that match selector but are also descendents of the same selector

Answer by Starx

You don’t need to build a plugin. use jQuery inbuilt .first() and as suggested by Mark, you can also use first selector :first

$("#yourselector ul").first();

Here is the usages in your case

$("#start").find("ul").first().css("background", "red");
   //For Short $("#start ul").first()

To use class filter, use the attribute selector

$("#start").find("ul[class=valid-result]").first().css("background", "red");
   //For Short $("#start ul[class=valid-result]").first()

Demo


Update

If you want to highlight only the outer ul’s with class valid-result then first() is not needed at all

$("#start ul[class=valid-result]").css("background", "red");

But, since the inner ul will also share the background on my example, you might have to set different background for inner ul‘s. Here is an example


Update 2

If you want to select the first level of the <ul> then

$("#start div").chilrent("ul"); //this will return the first level of ul inside the div
Read more

Nav menu bleeds out of container

Question by Mark Sandman

Morning again…,

Sorry to bother everyone but I need more help… I haven’t done any real coding in ages so here goes…

I’m trying to make a horizontal navigation menu, here’s my html

<nav>
<ul id="navmenu">
   <li><a href="" title="" class="selected">Link 1</a></li>
   <li><a href="" title="">Link 2</a></li>
   <li><a href="" title="">Link 3</a></li>
   <li><a href="" title="">Link 4</a></li>
   <li><a href="" title="">Link 5</a></li>
<ul>
<nav> 

now I have the following CSS

/* menu */
ul#navmenu{ 
    border-top:1px solid #FFF;
    background:#e60000;
    list-style: none;
    margin: 0;
    padding: 0;
    padding-left:30px;
}

ul#navmenu li{
    display:inline;

}

ul#navmenu li a{
    color:#fff;
    text-decoration:none;
    /*
    padding-left:15px;
    padding-right:15px;
    */
    padding:15px 15px 15px 15px;
}

ul#navmenu li a.selected{
    color:#e60000;
    text-decoration:none;
    /*
    padding-left:15px;
    padding-right:15px;
    */
    padding:15px 15px 15px 15px;
    background:#fff;
}

I want the links to sit in the center of the Li and look something like this:

enter image description here

However the containing UL doesn’t seem to contain the LIs, they bleed out of the container. I’ve played around with overflow and line heights but nothing seems to work… here’s a worst case scenario…

enter image description here

does any one have any ideas?

Answer by sandeep

give display:block to your <a> because <a> in an inline element so, inline element not take vertical margin, vertical padding, width & height

Check this http://jsfiddle.net/T8eNe/2/

but first close your UL & NAV

Answer by Starx

Give inline-block to your anchor

ul li a { display: inline-block; }
Read more

Add a Data-test-id attribute to a <td> in my Jquery

Question by Rammtin Avar

I have a Table, Textarea and a Button. When a user types inside the Textarea and then clicks on my Button the text gets added to the Table as a row with following code:

<script type="text/javascript">
 $(function() {
    $('#CustomButton').click(function() {
        $('#CustomPickedTable tbody').append(
            $('<tr/>',
             {
            click: function() {
                    $(this).remove();
                    },
                html: $('<td/>', {
                    text: $('#CustomQuestionText').val()
                })
            })
        );
        return false;
    });
});
</script>

When a user types inside the TextArea and then clicks on the Button is that my Table Tbody gets this <td>What user typed..</td> What I would like is that my table gets <td data-test-id="5">what user typed..</td>.

Is there any solutions for that in my jquery so my <td> gets an data-test-id attribute?

Thanks in advance!

Answer by Starx

You can do it this way

$('#CustomButton').click(function() {
    $('#CustomPickedTable tbody').append(
        $('<tr/>', {
            html: $("<td />", {
                html: $("#CustomQuestionText").val(),
                'data-attr-id': 5

            })
        })
    );
    return false;
});
Read more

Accessing lower level data in JSON

Question by SeasonEnds

I’ve done some searching, but I’ve been unable to fully understand how this is done. I am relatively new to jQuery and JSON. Basically, I have a massive JSON document that I am connecting to and displaying various data from it. The data I need is the Supplier Label, which is nested three levels down, and I’m unsure how to return it.

The JSON

    {
    "@order": "1",
    "category": {
        "@id": "204",
        "label": "Category 1",
        "suppliers": {
            "supplier": {
                "label": "Business 1",
                "customicons": [
                    {
                        "@id": "images/img2.jpeg",
                        "#text": "random icon"
                    }
                ]
            }
         }
       }
    },

Here’s the script that I’ve made to form an unordered list. I tried item.category.suppliers.supplier.label, which obviously isn’t working. Do I need to add some function that iterates through each sub level? How do I get to that label?

    <script type="text/javascript">
$(document).ready(function(){

    $.getJSON('jsonarray.json', 
    function(data) {

      var items = [];

      $.each(data, function(i,item) {

        items.push('<li id="' + item["@order"] + '"><label for="supplier"><input id="supplier" name="supplier" type="checkbox" class="checkbox"/>' + item.category.suppliers.supplier.label + '</label></li>');

      });

      $('<ul/>', {
        'class': 'checklist-supplier cl2',
        html: items.join('')
      }).appendTo('.list_filter_supplier_side');
    });

});
</script>

So, basically the question is how do I access sub level data in JSON using jQuery? Any clarification is greatly appreciated.

Answer by MattW

is the JSON in some sort of response? If so you can do something like this:

var d = {
"@order": "1",
"category": {
    "@id": "204",
    "label": "Category 1",
    "suppliers": {
        "supplier": {
            "label": "Business 1",
            "customicons": [
                {
                    "@id": "images/img2.jpeg",
                    "#text": "random icon"
                }
            ]
        }
     }
   }
}

//just show the label    
alert(d.category.suppliers.supplier.label);

jsFiddle Example

Answer by Starx

Except that, You are using the correct way of accessing the data

item.category.suppliers.supplier.label

Validate your JSON using jsonlint to confirm its validation

Read more
March 28, 2012

Not displaying data from mysql

Question by Ken

I have this table,

--------------------------------------------
|   products_id   |   related_products_ids |
| -----------------------------------------
|    1            |  1,2,3,4,6,            |
| -----------------------------------------
|    2            |   1,2,3,               |
| -----------------------------------------
|    3            |   1,2,                 |
-------------------------------------------

I want to display those related products in the product page. How can I do that?

Example, I’m in the product page where products_id is 1, i want to display the products from a table like table_name1 by related_products_ids.

I have used this code for displaying data,

    $sql = "SELECT related_products_ids FROM ".TABLE_RELATED_PRODUCTS." where products_id = '" . (int)$_GET["products_id"]."'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$lst_rp = explode(',', $row['related_products_ids']);
echo '<ul>';
foreach($lst_rp as $rp_id) {
  $res = "SELECT products_id, products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id='" . $rp_id . "'";
  $result1 = mysql_query($res);
  $row1 = mysql_fetch_array($result1);
  echo '<li>'.$row1['products_name'].'</li>';
}
echo '</ul>';

However, it displays nothing.. Is there something wrong with my code? Do you have any solution for this?

Thank you.

Answer by Starx

You have placed the actual database query section outside of the loop.

You should include this within the foreach loop, so that every time, a new query runs and you will receive the results as you anticipated.

foreach($lst_rp as $rp_id) {

    $res = "SELECT products_id, products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id='" . $rp_id . "'";
    $result1 = mysql_query($res);
    while($row1 = mysql_fetch_array($result1)) {
        echo $row1['products_name'];
    }

}

And one more thing, since you are using double quotes to wrap your query, you can shorten it two

$res = "SELECT products_id, products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id='$rp_id'";

Update

Use the following code to ensure the <li> is not empty

foreach($lst_rp as $rp_id) {
  $res = "SELECT products_id, products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id='" . $rp_id . "'";
  $result1 = mysql_query($res);
  $row1 = mysql_fetch_array($result1);
  echo !empty($row1['products_name']) ? '<li>'.$row1['products_name'].'</li>' : '';
}
Read more

jQuery function chaining unrelated objects

Question by jim tollan

I have of course searched SO for an answer to my ‘specific’ question but haven’t found anything that allows me to reach my desired goal. Basically, I’d like to be able to chain together function calls with the ability to add a ‘delay’ between those calls being issued. I’m figuring that something along the lines of a setTimeout() chain will be required. However, as these calls are aysnchronys, I obviously can’t simply chain those together and hope for a result. I did see reference to the built in jQuery queue and dequeue functions and figured that something might work based on that. Thus far, I’ve not been able to concoct anything that gets close to my requirement.

I’ve created a very basic example that demonstrates what I’m trying to achieve by chaining here (btw – jsfiddle is being a bit slow today):

http://jsfiddle.net/jimibt/wZeTT/

this uses nested setInterval calls, therefore is nasty and doesn’t scale. My nirvana would be a jquery extension method that had the following syntax (1st param being the function, 2nd param being the setTimout value delay):

$().chain($('#strap1').fadeIn(1300), 500)
     .chain($('#strap2').fadeIn(1300), 500)
     .chain($('#strap3').fadeIn(1300), 500)
     .start();

Now I know that there is a delay() funtion in jquery, but this only works (to my knowledge) as part of a chain against a single selector and thus can’t be used to chain together multiple unconnected elements as per my example. I did see this linked SO question that is CLOSE to what I was hoping for, but still not wrapped up in the way I’d like:

Chaining jQuery animations that affect different elements

Any thoughts??

Answer by Starx

You can use callbacks like this

$('#strap1').delay(500).fadeIn(1300,function(){
    $('#strap2').delay(500).fadeIn(1300,function(){
        $('#strap3').delay(500).fadeIn(1300);
    });
});

Usage [demo]

$('#strap1').delay(500).fadeIn(1300,function(){
    $('#strap2').delay(500).fadeIn(1300,function(){
        $('#strap3').delay(500).fadeIn(1300, function() {
            $('#strapline').css({
                'color': '#fff'
            }).animate({
                'color': color
            }, 3000);            
        });
    });
});
Read more
...

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