Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

how to validate object in jquery

how to validate object in jquery

Problem

I am adding arbitrary data to li element using jquery as:

  if($("li").data('family').$(this).text()==$(this).text()){
        $("li").removeData('family',{'persons':''}); // I know this is wrong!
        // any idea how to remove data from this object 
    }else{
        //this part adds data which is not working fine 
        $("li").data('family',{$(this).text():$(this).text(),
            'cat':'family'
        });
    } 

above I m trying to validate whether the value already exits or not if exits remove it. I am facing 1 problem:

  1. How to add / remove key value same from object

Thanks in advance!

Problem courtesy of: sandip

Solution

Try this

$("#cat-family ul li").live("click", function() {
            var $ul = $(this).closest('ul');
            var family = $ul.data('family');
            if (!family) {
                family = {
                    'cat' : 'family'
                };
                $ul.data('family', family);
            }

            var text = $(this).text();
            if (family[text]) {
                delete family[text];
            } else {
                family[text] = text;
            }
            console.log(this, $ul.data().family);
        });

Demo: Fiddle

Solution courtesy of: Arun P Johny

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

how to validate object in jquery

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×