...

Hi! I’m Starx

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

how to get the unique items in jquery

Question by vipin katiyar

I have the html file like below:

<div id="ultreecurri" style="float:left;">
<ul>

<li id="li1" class="popupul" style="text-align: left;">International</li>
<li id="li10" class="popupul" style="text-align: left;">Science</li>
<li id="li332" class="popupul" style="text-align: left;">Physics</li>
<li id="li2" class="popupul" style="text-align: left;">Africa</li>
<li id="li3" class="popupul" style="text-align: left;">Asia</li>
<li id="li5" class="popupul" style="text-align: left;">Caribbean</li>
<li id="li8" class="popupul" style="text-align: left;">North America</li>
<li id="li9" class="popupul" style="text-align: left;">South America</li>
<li id="li1" class="popupul" style="text-align: left;">International</li>
<li id="li10" class="popupul" style="text-align: left;"> Science</li>
<li id="li332" class="popupul" style="text-align: left;">Physics</li>
<li id="li2" class="popupul" style="text-align: left;">Africa</li>
<li id="li3" class="popupul" style="text-align: left;">Asia</li>
<li id="li5" class="popupul" style="text-align: left;">Caribbean</li>
<li id="li8" class="popupul" style="text-align: left;">North America</li>
<li id="li9" class="popupul" style="text-align: left;">South America</li>
 </ul>
</div>

how can i get the unique text of li items according to their liids.

Answer by Starx

The markup contains so many duplicated ID so, it is not a valid Markup. Instead I suggest you to remove the duplicate element, thus having a unique element on an array.

Here is a snippet for this purpose.

var list = {};
$('li').each(function() {
    var id = $(this).attr('id');
    if (list[id])
        $(this).remove();
    else
        list[id] = $(this);
});
Read more
June 3, 2012

Check if url contains parameters

Question by Puyol

Possible Duplicate:
keeping url parameters during pagination

I want to add a parameter to the current url with php, but how do I know if the url already contains a parameter?

Example:

foobar.com/foo/bar/index.php => foobar.com/foo/bar/index.php?myparameter=5
foobar.com/index.php?foo=7 => foobar.com/index.php?foo=7&myparameter=5

The main problem is that I don’t know if I need to add a “?”.

My code (found it somewhere, but it doesn’t work):

<?php   if(/?/.test(self.location.href)){ //if url contains ?
    $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&myparameter=5";
} else {
    $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]?myparameter=5"; 
}?>

Answer by Starx

The URL parameters and received from a global variable called $_GET which is in fact an array. So, to know if a URL contains a parameter, you can use isset() function.

if (isset($_GET['yourparametername'])) {
    //The parameter you need is present
}

After wards, you can create separate array of such parameter you need to attach to a URL. LIke

if(isset($_GET['param1'])) {
    \The parameter you need is present
    $attachList['param1'] = $_GET['param1'];
}
if(isset($_GET['param2'])) {
    $attachList['param2'] = $_GET['param2];
}

Now, to know whether or not, you need a ? symbol, just count this array

if(count($attachList)) {
    $link .= "?";
    // and so on
}

Update:

To know if any parameter is set, just count the $_GET

if(count($_GET)) {
     //some parameters are set
}
Read more

How to create a namedquery of manytomany entity?

Question by Khushbu Joshi

Brand

public class Brand implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "BrandID", nullable = false)
    private Integer brandID;
    @Basic(optional = false)
    @Column(name = "BrandName", nullable = false, length = 100)
    private String brandName;
    @Basic(optional = false)
    @Column(name = "Description", nullable = false, length = 1000)
    private String description;
    @Column(name = "Is_Visible")
    private Boolean isVisible;
    @JoinTable(name = "brandcategory", joinColumns = {
        @JoinColumn(name = "BrandID", referencedColumnName = "BrandID")}, inverseJoinColumns = {
        @JoinColumn(name = "CategoryID", referencedColumnName = "CategoryID")})
    @ManyToMany(fetch = FetchType.EAGER)
    private Collection<Category> categoryCollection;
    @OneToMany(mappedBy = "brand", fetch = FetchType.EAGER)
    private Collection<Product> productCollection;

I want to retrive the Brand IDs from table brandcategory whoes categoryID = :categoryID
how can i createnamed query for it in entity brand?

this does not work:

@NamedQuery(name = "Brand.getBrandListByCategory",
            query = "SELECT b FROM Brand b WHERE b.brandID =
            (SELECT bc.brandID
             FROM b.brandctegory bc
             WHERE bc.category.categoryID = :categoryID)")

Answer by JB Nizet

If I understand correctly, you want all the brands belonging to a category. Why don’t you simply make the association bidirectional. You could then just do:

Category category = em.find(Category.class, categoryId);
return category.getBrands();

If it’s unidirectional, then you’ll need a query, but it’s much simpler that the one you tried:

select b from Brand b inner join b.categoryCollection category 
where category.id = :categoryId;

Your query doesn’t make sense: it uses a non-existing association (b.brandcategory). Remember that JPQL uses entities, their persistent fields and associations to other entities. And nothing else. Tables don’t exist in JPQL.

Answer by Starx

AFAIK, you cant go out of a entity boundary, when creating queries in entity class.

Instead use .createNativeQuery() method of the entity manager, to create complex and mixed queries.

Read more
May 31, 2012

jQuery setInterval

Question by gkunno

I have a jQuery function that flips an element and then turn it back after a few seconds, however there is multiple elements with the same “flip” tag and the setInterval elements flip all the elements back after the first click. How could i implement the flip effect to turn only the elements that have been clicked in e kind of flow, so that not all elements flip after the delay. The code is:

$(document).ready(function() {

    $('.click').toggle(function() //on click functions => toggle elements
    {           

        setTimeout( function() { // trigger the flip-back after delay (1500ms)
        $('.flip').trigger('click');
        }, 1500) 

        $this = $(this);
        $this.addClass('flip');
        $this.children('.front').delay(600).hide(0);
        $this.children('.back').delay(600).show(0);

    },          
        function() 
        {

        $this = $(this);
        $this.removeClass('flip');
        $this.children('.front').delay(600).show(0);
        $this.children('.back').delay(600).hide(0);

        });  
});

My intention is that the elements would flip back after the delay, but now all the clicked elements flip back after the delay, even though they are only visible for the time – delay. Hops this makes sense 🙂

Thnx for any help!

Answer by Starx

Use, $(this) or this to refer the current item that is click. Also, the extra function is not needed, just use toggleClass() to apply/remove the class.

$('.click').click(function() //on click functions => toggle elements
{           

    var $this = $(this);
    setTimeout( function() { // trigger the flip-back after delay (1500ms)
        $this.trigger('click');
    }, 1500);

    $this.toggleClass('flip');
    $this.children('.front').delay(600).hide(0);
    $this.children('.back').delay(600).show(0);

});
Read more

How to share content from our site to google plus

Question by keerthi

How to share content from our site to google plus

I tried it like this

<a href="javascript:void(0);" onclick="window.open('https://plus.google.com/share?url=<?php echo urlencode('http://example.com');?>&via=example', 'Share on Google Plus', 'width=600,height=400,left=450').focus();" >

Here I can not share content from my site. How it is possible with this?
I want to share content (example: hello) to goggle plus with sharing capability

Answer by Starx

Its been some time since the Google has brought its share button. You can find this, on their developer’s page. [Here]

Paste the generated code on your web page, then link of the page will be automatically received by the API.

Read more

Best way to save encrypt/decrypt key?

Question by Kenneth Poulsen

I’m developing a wordpress plugin.
In that plugin the user need to type some important login details, which I will use in a cron-job.

I will of cause like to encrypt the password, and found this useful stuff:
Best way to use PHP to encrypt and decrypt?

However, how should I save the key?
I can’t save it in a file, since all files will be replaced when the user update the plugin.
And save it in the database, well – that’s not exactly smart i guess.

Any suggestions?

Answer by Starx

I think its better, if you save the key on the database table. About the part of securing the database and making sure that the data in the table will only be accessible by the authorized person, You can create a second user, with the privilege of accessing and reading such vital tables.

Therefore, create a separate user, who will have the authority to access the table and its contents. Now, use the website, with a different user, and switch to a administrative database user, when you need to access the encryption key and other vital information.

Read more
May 30, 2012

CSS disable text selection

Question by Neil

Currently i have put this in the body tag to disable text selections

body{
 -webkit-user-select: none;  
  -moz-user-select: none;    
  -ms-user-select: none;      
  user-select: none;
}

However my input and textarea boxes are now unselectable .How can i only make these input elements selectable and the reset unselectable

Answer by Someth Victory

Don’t apply these properties to the whole body. Move them to a class and apply that class to the elements you want to disable select:

.disable-select {
  -webkit-user-select: none;  
  -moz-user-select: none;    
  -ms-user-select: none;      
  user-select: none;
}

Answer by Starx

Use a wild card selector * for this purpose.

#div * { /* Narrowing, to specific elements, like  input, textarea is PREFFERED */
 -webkit-user-select: none;  
  -moz-user-select: none;    
  -ms-user-select: none;      
  user-select: none;
}

Now, every element inside a div with id div will have no selection.

Demo

Read more
May 29, 2012

How to make application browser compatible

Question by Rajesh

I am building an application which is working fine in IE8 and Mozilla Firefox,but not in IE7. I like firebug and I like to debug my application using that,but currently I am struggling with browser compatibility thing. I found that application developed is working in IE8,FF11 but not in IE7(mainly layout is highlighly impacted). I am using jquery for browser related functionality and the jquery thing seems to be working..what shall I do to make layout working fine in IE7?
Framework used is spring3,hibernate..
I have huge set of CSS I dont think pasting that here will be any helpful.I have used postion relative and used top,left position some things..padding and margin are used but not that much..is that the cause? what is the possible suggestion? why IE7 and IE8 render things in different way? Shall I load different set of CSS for IE7,using spring? is it good solution?if yes then how to do that in spring?
Shall i discard using firebug and rely on IE8 debugger because our client mainly use IE7

Answer by Starx

Browser compatibility is a very lengthy topic and it covers more than one area to perform correctly.

If IE 7 or IE browsers are your only problem, then CSS Conditional comments is the PERFECT solution for you.

Create a separate stylesheet, with all the neccessary fixes for IE7 browser. Then call the script is such a way, only IE 7 will render it.

<!--[if IE 7]>
    <link rel="stylesheet" type="text/css" media="screen" href="ie7fix.css" />
<![endif]-->

Now, the above stylesheet is only apply, in case if the browser is IE 7. So, all your fixes will be applied, thus the layout will be fixed. 🙂


To read more about conditional comments, read this article.

Read more

How to get last li's anchor tag with simple dom html in php

Question by Ravi Kotwani

I am crawling a web with the help of simple dom in PHP.

I am getting following html with the help curl:

<ul><li>1</li><li>2</li><li>3</li><li><a href="http:abc.com">4</a></li></ul>

Now, I need to href (link) of anchor tag which is in the last li of this ul with the help of simple dom object. Please provide me syntax how can I do this?

I have tried with the following code but i am not able to find the last li…

require_once 'simple_html_dom.php';
        $html = "<ul><li>1</li><li>2</li><li>3</li><li><a href="http:abc.com">4</a></li></ul>";
        $oDocumentModel = new simple_html_dom();
        $oDocumentModel->load($html);
        $ul = $oDocumentModel->find('ul',0);

Answer by Sanjay

You can loop through the li and convert it in array and find the last element. if you have smaller set of li like…

require_once 'simple_html_dom.php';
$html = "<ul><li>1</li><li>2</li><li>3</li><li><a href='http:abc.com'>4</a></li></ul>";
$oDocumentModel = new simple_html_dom();
$oDocumentModel->load($html);
$ul = $oDocumentModel->find('ul',0);

$items = array();
foreach( $ul->find('li') as $li ){
    $items[] = $li->plaintext;
}
$last = end($items);
print_r($last);

Or you can use lastChild() just go through the http://simplehtmldom.sourceforge.net/manual_api.htm

Answer by Starx

You can extract the link this way.

$ul = $oDocumentModel->find('ul',0);
$a = $ul -> lastChild() -> find('a'. 0);
$href = $a -> href;
Read more

jQuery Validate – Success event?

Question by Probocop

I am using the jQuery Validate plugin on my site, and then submitting the form via ajax. Is there an event I can use when the entire form is valid?

Answer by Starx

There is no event for this. Just check the status using a simple if statement.

if($("form").valid()) {
 //go ahead
}

But, if you are trying to have a workaround solution to catch the valid event, you can do something like this

$("form").submit(fucntion() {
    if($(this).valid()) {
       //go ahead
    } else {
       //do some error handling
    }
});
Read more
...

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