12 jQuery Questions and Answers You Should Be Reading on StackOverflow

Hi guys! Below are twelve of the jQuery related questions and answers on StackOverflow that I found very useful during development. I opted to compile them here because I feel good reading those brilliant questions and answers by coders from around the world. Enjoy!

  1. How would I know if an element is hidden?

Sometimes you want some elements of your page to be visible, and if it is not visible, you want to tell the user about it. For example, a user must have a selection of data first before proceeding to new operation. If he has no selection (div is hidden), you can do a prompt that he must select something.

  1. How do I get selected text in select box?

Ah, a drop-down list? Link # 2 above shows you how to get the user drop down list selection.

  1. How to redirect a page?

Useful if you want to your users to see a page after an AJAX request, or you just want them to be redirected. I’ve written another example here, jQuery: Redirect onClick

  1. How would I know if a checkbox is checked or unchecked?

For example, you want to enable a delete button if the user selected at least one data to delete, else, the delete button is disabled. I’ve written another example here: Check or Uncheck Checkboxes with jQuery And Get Selected with PHP

  1. How to select a child element?

Teaches us how to select a child element and do it with faster performance (see the comment by Paul Irish).

  1. event.preventDefault() vs. return false

I use return false; when I want to prevent a page refresh after clicking a submit button and doing an AJAX request.

  1. Example of using jQuery .closest() method.

I use jQuery .closest() method on selecting an element within a table with several rows. I probably have to write an example in another blog post, ha!

  1. How would I know the existence of an element?

Useful if you want to perform something if an element exists in your page. The faster way is using if ($(selector).length) {}

  1. How would I know which radio button is selected?

This is how you will know if a user is a male or female, using jQuery!

  1. How to select multiple classes?

Sometimes you want to to something to multiple classes at once. There’s another example here.

  1. How to select an element by its name, not by class or id?

If you’re more familiar with an element’s name or don’t want to add a class or id name, you can use this cool technique.

  1. What if Google hosted jQuery is blocked?

In some countries, Google’s domain name is banned. So if you are using a Google hosted jQuery library, you’re site won’t work. Link # 12 above shows you the fall back.

This can be the first part of the list, you can add more in the comments section below, or on our Facebook, Twitter or Google+!
And as always, thanks for reading!

12 Animated HTML and CSS Logo Examples You’ll Love

I'm still amazed by these people creating and coding logos using only the HTML and CSS technology, I was like, look Ma, no Images and JavaScript!

So here are some of those amazing HTML and CSS logo examples that I recently found on the web (some are not actually logos but they can be used as logos). Click the title of each items below to view its code and live demo!

HTML and CSS Logo Examples:

1. Optical Spinner

1-optical-spinner-animated-css-html-logo-1

2. Alien Bot

animated-css-html-logo-2

3. Tape Recorder

3-tape-recorder-animated-css-html-logo

4. Jarvis

3-jarvis-animated-css-html-logo

5. Snow Pyramid

5-snow-pyramid-animated-css-html-logo

6. Psychedelic Spiral Wormhole

6-black-hole-animated-css-html-logo

7. Lemon Slice in Water

2-lemon-slice-in-water-animated-css-html-logo-1

8. Lazy Cute Red Pet

8-lazy-cute-red-pet-animated-css-html-logo-1

9. Smooth Camera

9-smooth-camera-animated-css-html-logo-1

10. Minion with Superman Mode - JavaScript were used only for changing to Superman mode.

10-minion-superman-animated-css-html-logo

11. Rotating Window

11-windows-animated-css-html-logo

12. Pixel Perfect Ubuntu

12-pixel-perfect-ubuntu-animated-css-html-logo

I want to grow this list. If ever you want to add your own work or you know something the same or more awesome, please drop it in the comments section below! Any comments and suggestions are also welcome!

You think they are awesome too? Feel free to share this awesome HTML and CSS logo examples!

Creating Social Media Icons for Your Website using CSS

In almost every website we see today, there are links to their social media accounts. I think it is a standard now. It’s like, you’re not cool if you don’t have a Facebook and Twitter account!

Recently, I was using Google drive to host my CSS and image files. Now, I removed it. Why?

Because Google drive slows down my website! During the use of Google drive hosted CSS and images, the average load time of this wesbite is around 10-20 seconds for new visitors.

After I removed it, it is now around less than 5 seconds!

Creating Social Media Icons for Your Website using CSS
My new social media icons. :)

I decided not to use any third party CSS code. I wanted to create my own social media icons, and I did! (see the screenshot above or the lower right corner of this page for live demo)

I think the icons I made are so cute that I thought of sharing it to you guys (I appreciate a tweet, like or +1 before you use it!). It loads fast, contains few lines of CSS and HTML code, and it doesn’t use any images! Here’s how I did it, below are the CSS and HTML code I used.

HTML code:

<div id="socialMediaIcons">
 
    <a class="facebook" href="https://www.facebook.com/CodeOfANinja" title="Facebook" target="_blank">f</a>
     
    <a class="twitter" href="http://twitter.com/ninjazhai" title="Twitter" target="_blank">t</a>
     
    <a class="googleplus" href="https://plus.google.com/b/101266899643014043497/101266899643014043497/posts" title="Google+" target="_blank">g+</a>
     
    <a class="rss" href="https://www.codeofaninja.com/feeds/posts/default?alt=rss" title="RSS" target="_blank">r</a>
     
    <a class="email" href="http://feedburner.google.com/fb/a/mailverify?uri=TheCodeOfANinja" title="Email" target="_blank">@</a>
     
</div>

CSS code:

#socialMediaIcons{
    margin: 0 auto;
    text-align:center;
}
 
#socialMediaIcons a{
    border-radius: 3px;
    color:#fff;
    font-family: arial;
    font-size:1em;
    height:2.5em;
    padding:1em;
    text-align:center;
    width:2.5em;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
}
 
#socialMediaIcons a:hover{
    color:#fff;
    text-decoration:none;
}
 
.facebook { background:#4c66a4; padding:2px 10px; }
.twitter { background:#33bcef; padding:2px 10px; }
.googleplus { background:#D2412E; padding:2px 3px; }
.rss { background:#fa9b39; padding: 2px 6px; }
.email { background:#00D8CC; padidng: 2px 6px; }

And… that’s how I created my new social media icons using CSS!

CSS3 Rotate Image On Hover

Have you seen our logo on the upper left corner? Try to hover on it, it will rotate 360 degrees. Looks cool? In this quick post, I’m going to show you how I did that using CSS3.

CSS:

#linkWrapRotator img {
     -webkit-transition: all 1s ease-in-out;
     -moz-transition: all 1s ease-in-out; 
     -o-transition: all 1s ease-in-out; 
     -ms-transition: all 1s ease-in-out; 
}
 
#linkWrapRotator img:hover { 
     -webkit-transform: rotate(360deg); 
     -moz-transform: rotate(360deg); 
     -o-transform: rotate(360deg);
     -ms-transform: rotate(360deg); 
}

HTML used:

<a href='https://www.codeofaninja.com/' id='linkWrapRotator'>
     <img src='https://lh6.googleusercontent.com/-Q0p2PeGBLLg/UTr5zOvggSI/AAAAAAAAEeM/SrYuO-cYWQU/s205/ninja-icon200x200.png' />
</a>

You can also do the rotation in other degrees, not on 360, just change the value of “rotate” in our code. For example, you can do rotate(180deg);

Just play with it!

Now that was fast and easy, I know there are other ways to do it, like using jQuery. There would also be some variations in doing this, such as not having a "a" tag.

Please share your own beautiful work, experience and cases on the comment section below!

Resposive Web Design Testing Tools

Hi guys! Today we have a guest post from Marykris de Leon, you can find more about her at the end of the post, please read below!
Hello geeks! This is a quick guide on how you can test your responsive website without actual gadgets or devices. I personally recommend these tools for testing on devices such as smartphones, laptops, tablets, and TVs. We are going to have two categories: Browser Extensions and Online Tools.

Resposive Web Design Testing Tools

Browser Extensions

1. Internet Explorer – You should have Microsoft Internet Explorer Developer Toolbar which can be downloaded on this link: Internet Explorer Developer Toolbar. After installing, you have to press F12 on your keyboard to use this tool.

EI Developer Toolbar.
EI Developer Toolbar.

2. Firefox - For Firefox users, you may use Firesizer which can be downloaded on this link: Firesizer. To use this, you have to enable your addon bar:

Enable Add-on bar for Firesizer.
Enable Add-on bar for Firesizer.

Then on the add-on bar look for the Firesizer function which is located on the lower right corner of Firefox, you have to right click to customize the sizes.

Using Firesizer.
Using Firesizer.

You may also try Responsive Design View on Firefox > Web Developer > Responsive Web Design or Ctrl + Shift + M for keyboard shortcut.

Firefox Responsive Web Design View.
Firefox Responsive Web Design View.

3. Google Chrome – Chrome has Window Resizer, you can install this awesome Chrome extension from this link: Window Resizer

Google Chrome Window Resizer.
Google Chrome Window Resizer.

Online Tools

1. Screenfly – Allows you to enter your website URL and gives you many view options for testing such as Netbooks, Desktop, Kindle Fire, iPad 1-3/Mini, Nexus 7, Motorola Razr, Blackberry, LG optimus, Galaxy SIII, iPhones, and Television views (480p, 720p, 1080p). It also allows you to specify custom screen size and rotate the screen view. This is my favorite online testing tool.

Screenfly.
Screenfly.

2. Responsinator – Also allows you to enter your website URL (located on the upper left corner) and gives you the available views in one load which is kinda fast and convenient, you just have to scroll down. The available views is limited to iPhone (3,4,5), iPad, Kindle, and Samsung Galaxy. All has portrait and landscape mode.

Responsinator.
Responsinator.

3. Responsivetest- Also allows you to enter your responsive website URL (located on the upper left corner) and loads the view one at a time, depends on your device selection. Screens are limited to XGA, WXGA, iPad, Kindle Fire, iPhone and Android phones (320 x 240 and 515 x 295), also has landscape and portrait mode.

responsivetest.net
responsivetest.net

By the way, the example website we used in this post is this responsive web design live demo. The tutorial for coding a responsive website can be found here: Coding A Responsive Website Design.

Let us know in the comments what testing tools do you use? :)

About Marykris

Marykris De Leon is a professional Systems Analyst and Web Developer for the past three years. You can follow her on Facebook, Twitter and Google+

How To Make Responsive Web Design CSS Code?

In today’s tutorial, I’m going to show you a systematic and very simple way to create a responsive website with CSS3 media queries and HTML5.

Responsive web design has been around for few years now and is widely accepted as a new standard when building a modern website.

Coding A Responsive Website Design

For the “live demo”, please try to resize your browser to see the page’s responsiveness.

I want to give you a brief definition of what a responsive web design is, if you already know what it is, you may skip this part and jump to the “Let’s code” section below. Well, for me, responsive web design is a way to show your web site’s content in an easy-to-understand manner regardless of what device views it.

For example, a visitor of your website must feel comfortable when viewing the same website for any type of devices (with different screen sizes) he has. Example of those devices include:

  • Android phones
  • iPhones
  • 7″ tablets
  • 10″ tablets
  • iPads
  • Desktop computers
  • and many more devices that can view a web page.

Other points to consider…

  • Your website should not have a horizontal scrollbar.
  • Users must not use the zoom tool to view your site’s contents.

By the way, if you want to test the live demo on different devices easily, you can use the tools described on this link: Responsive Web Design Testing Tools.

Let’s code.

Step 1: It is important to build your website for the smallest device possible first. Build the website for smart phones. You can view a live demo of our step 1 here.

<!DOCTYPE HTML>
<html>
     <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
          <meta name="viewport" content="width=device-width">
          
          <title>Your Website</title>
          
          <style>
               
          /* misc start */
          *{
               margin:0px;
               padding:0px
          }
          
          body{
               font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
          }
          
          .media1140px{
               background-color:#CE9429;
          }
          
          .media768px{
               background-color:#EDD49A;
          }
          
          .media480px{
               background-color:#EFEF34;
          }
          
          .media300px{
               background-color:#82EAFF;
          }
          
          .media1140px, .media768px, .media480px, .media300px{
               padding:15px;
          }
          
          p{
               margin:0 0 20px 0;
          }
          
          .clearb{
               clear:both;
          }
          /* misc end */
          
          
          
          
          
          
          /* header start */
          #mainHeader{
               background-color:#82EAFF;
               padding:0.5em;
               overflow:auto;
          }
           
          /* to make our logo resize automatically */
          #responsiveLogo{
               width:100%;
          }
          
          #responsiveLogo img{
               max-height: 100%;
               max-width: 100%;
          }
          /* header end */
          
          
          
          
          
          /* navigation start */
          nav{
               float:left;
               width:100%;
          }
          
          nav ul{
               list-style-type:none;
               padding:0;
          }
 
          nav ul li{
          
          }
 
          nav ul li a{
               background-color:green;
               border:thin solid #fff;
               color:#fff;
               display:block;
               height:3em;
               line-height:3em;
               text-align:center;
               text-decoration:none;
               width:100%;
          }
          
          nav ul li a:hover{
               background-color:yellow;
               color:#000;
          }
          /* navigation end */
          
          
          
          
          
          /* middle section start */
          #mainSection{
               background-color: #D9F8F2;
               float: left;
               width: 96%;
          }
          
          #sideBox1{
               background-color: #C9A449;
               width: 96%;
          }
          
          #mainSection, #sideBox1{
               overflow: auto;
               padding:2%;
          }
          /* middle section end */
          
          
          
          /* footer start */
          footer{
               background-color:orange;
               height:50px;
               line-height:50px;
               text-align:center;
               width:100%;
          }
          /* footer end */
               
          </style>
          
     </head>
<body>
 
     <header id='mainHeader'>
     
          <div id='responsiveLogo'>
               <img src='images/logo4.png' />
          </div>
          <nav>
               <ul>
                    <li><a href="#home">Home</a></li>
                    <li><a href="#news">News</a></li>
                    <li><a href="#contact">Contact</a></li>
                    <li><a href="#about">About</a></li>
               </ul>
          </nav>
     </header>
     
     <section id='mainSection'>
 
          <article>
               <header>
                    <h2>About The Code Of A Ninja</h2>
                    <p>Posted on <time datetime="2003-01-01T16:31:24+02:00">January 1st, 2013</time> by <a href="#">Mike</a> - <a href="#comments">173 comments</a></p>
               </header>
               <p>
                    <div class='media1140px'>@media 1140px</div>
                    <div class='media768px'>@media 768px</div>
                    <div class='media480px'>@media 480px</div>
                    <div class='media300px'>@media 300px</div>
               </p>
               <p>
                    My name is Mike Dalisay, a 22 year old Software Developer (<a href="http://en.wikipedia.org/wiki/Web_developer">Web</a> and
                    <a href="http://developer.android.com/index.html">Android</a>) from The Philippines.
                    My posts here are mainly notes to self and for <i>anyone else</i> that may find them useful.
               </p>
               <p>
                    This blog contains programming tutorials, codes, demos, scripts, how-to's, tips, tricks, code downloads and other fun stuff
                    related to web and android apps <a href="http://en.wikipedia.org/wiki/Software_development">development</a>.
               </p>
               <p>
                    Most of my time is spent with PHP, MySQL, AJAX, HTML, CSS, jQuery, JavaScript, XML, Web Design, Android, JAVA and some
                    other Open source software projects related to Web and Android apps development.
               </p>
               <p>
                    You can leave a comment, <a href="http://twitter.com/ninjazhai">follow</a> or <a href="https://www.facebook.com/pages/the-code-of-a-ninja/107786425949934">subscribe</a>
                    to this blog. Take care. :) 
               </p>
          </article>
 
     </section>
 
     <aside id='sideBox1'>
          <h2>The Blogger</h2>
          <p>This is your side bar. You can add your information or links here.</p>
     </aside>
 
     <div class='clearb'></div>
     
     <footer>
          <p>Copyright 2013 - Game Note</p>
     </footer>
 
</body>
</html>

After doing the code above, our webpage is not yet responsive. You won’t see the magic even if you resize your browser. By the way, you can also include the CSS code as external file.

Step 2: Now let’s create the website layout for a type of device next to a smart phone, maybe we can consider a 7″ tablets as one. You can view a live demo of your step 2 here.

We’ll just add the following CSS:

/* 
-can be for 7 inch tablets
-This CSS will apply for devices with the minimum width of 480 pixels
 */
@media only screen and (min-width: 480px) {
     #mainHeader {
          background-color:#EFEF34;
     }
     
     nav ul li{
          float:left;
          width:25%;
     }
}

Now if you’ll resize your browser, you can see that your website is already responsive in two ways.

Step 3: Now we will create the website layout for another type of screen next to 7″ tablets, we can consider the iPad or 10″ tablets in portrait mode. Our step 3 live demo is here.

Please add the following CSS:

/*
-10 inch tablets
-This CSS will apply for devices with the minimum width of 768 pixels
*/
@media only screen and (min-width: 768px) {
     #mainHeader {
          background-color:#EDD49A;
     }
     
     #mainSection{
          float: left;
          width: 61%;
     }
     
     #sideBox1{
          float: right;
          width: 30%;
     }
     
}

Now our website is responsive in three ways. Try to re-size your browser again.

Step 4: Now we will create the website for desktop computers, laptops or 10″ tablets in landscape mode.

/*
-Desktop computers
-This CSS will apply for devices with the minimum width of 1140 pixels
*/
@media only screen and (min-width: 1140px) {
     #mainHeader {
          background-color:#CE9429;
     }
     
     #responsiveLogo{
          float:left;
          width:30%;
     }
     
     nav{
          float:left;
          width:70%;
     }
     
     nav ul{
          margin:1.5em 0 0 0;
     }
}

Complete web page code:

<!DOCTYPE HTML>
<html>
     <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
          <meta name="viewport" content="width=device-width">
          
          <title>Your Website</title>
          
          <style>
               
          /* misc start */
          *{
               margin:0px;
               padding:0px
          }
          
          body{
               font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
          }
          
          .media1140px{
               background-color:#CE9429;
          }
          
          .media768px{
               background-color:#EDD49A;
          }
          
          .media480px{
               background-color:#EFEF34;
          }
          
          .media300px{
               background-color:#82EAFF;
          }
          
          .media1140px, .media768px, .media480px, .media300px{
               padding:15px;
          }
          
          p{
               margin:0 0 20px 0;
          }
          
          .clearb{
               clear:both;
          }
          /* misc end */
          
          
          
          
          
          
          /* header start */
          #mainHeader{
               background-color:#82EAFF;
               padding:0.5em;
               overflow:auto;
          }
          
          #responsiveLogo{
               width:100%;
          }
          
          #responsiveLogo img{
               max-height: 100%;
               max-width: 100%;
          }
          /* header end */
          
          
          
          
          
          /* navigation start */
          nav{
               float:left;
               width:100%;
          }
          
          nav ul{
               list-style-type:none;
               padding:0;
          }
 
          nav ul li{
          
          }
 
          nav ul li a{
               background-color:green;
               border:thin solid #fff;
               color:#fff;
               display:block;
               height:3em;
               line-height:3em;
               text-align:center;
               text-decoration:none;
               width:100%;
          }
          
          nav ul li a:hover{
               background-color:yellow;
               color:#000;
          }
          /* navigation end */
          
          
          
          
          
          /* middle section start */
          #mainSection{
               background-color: #D9F8F2;
               float: left;
               width: 96%;
          }
          
          #sideBox1{
               background-color: #C9A449;
               width: 96%;
          }
          
          #mainSection, #sideBox1{
               overflow: auto;
               padding:2%;
          }
          /* middle section end */
          
          
          
          /* footer start */
          footer{
               background-color:orange;
               height:50px;
               line-height:50px;
               text-align:center;
               width:100%;
          }
          /* footer end */
          
          
          
          
          
          
          
          /* @media start */
          
          /* we don't need to specify for smartphones, that's our default layout */
          
          /*
          -7 inch tablets
          -This CSS will apply for devices with the minimum width of 480 pixels
          */
          @media only screen and (min-width: 480px) {
               #mainHeader {
                    background-color:#EFEF34;
               }
               
               nav ul li{
                    float:left;
                    width:25%;
               }
          }
          
          /*
          -10 inch tablets
          -This CSS will apply for devices with the minimum width of 768 pixels
          */
          @media only screen and (min-width: 768px) {
               #mainHeader {
                    background-color:#EDD49A;
               }
               
               #mainSection{
                    float: left;
                    width: 61%;
               }
               
               #sideBox1{
                    float: right;
                    width: 30%;
               }
               
               
          }
          
          /*
          -Desktop computers
          -This CSS will apply for devices with the minimum width of 1140 pixels
          */
          @media only screen and (min-width: 1140px) {
               #mainHeader {
                    background-color:#CE9429;
               }
               
               #responsiveLogo{
                    float:left;
                    width:30%;
               }
               
               nav{
                    float:left;
                    width:70%;
               }
               
               nav ul{
                    margin:1.5em 0 0 0;
               }
          }
          
          /* @media end */
               
          </style>
          
     </head>
<body>
 
     <header id='mainHeader'>
     
          <div id='responsiveLogo'>
               <img src='images/logo4.png' />
          </div>
          <nav>
               <ul>
                    <li><a href="#home">Home</a></li>
                    <li><a href="#news">News</a></li>
                    <li><a href="#contact">Contact</a></li>
                    <li><a href="#about">About</a></li>
               </ul>
          </nav>
     </header>
     
     <section id='mainSection'>
 
          <article>
               <header>
                    <h2>About The Code Of A Ninja</h2>
                    <p>Posted on <time datetime="2003-01-01T16:31:24+02:00">January 1st, 2013</time> by <a href="#">Mike</a> - <a href="#comments">173 comments</a></p>
               </header>
               <p>
                    <div class='media1140px'>@media 1140px</div>
                    <div class='media768px'>@media 768px</div>
                    <div class='media480px'>@media 480px</div>
                    <div class='media300px'>@media 300px</div>
               </p>
               <p>
                    My name is Mike Dalisay, a 22 year old Software Developer (<a href="http://en.wikipedia.org/wiki/Web_developer">Web</a> and
                    <a href="http://developer.android.com/index.html">Android</a>) from The Philippines.
                    My posts here are mainly notes to self and for <i>anyone else</i> that may find them useful.
               </p>
               <p>
                    This blog contains programming tutorials, codes, demos, scripts, how-to's, tips, tricks, code downloads and other fun stuff
                    related to web and android apps <a href="http://en.wikipedia.org/wiki/Software_development">development</a>.
               </p>
               <p>
                    Most of my time is spent with PHP, MySQL, AJAX, HTML, CSS, jQuery, JavaScript, XML, Web Design, Android, JAVA and some
                    other Open source software projects related to Web and Android apps development.
               </p>
               <p>
                    You can leave a comment, <a href="http://twitter.com/ninjazhai">follow</a> or <a href="https://www.facebook.com/pages/the-code-of-a-ninja/107786425949934">subscribe</a>
                    to this blog. Take care. :) 
               </p>
          </article>
 
     </section>
 
     <aside id='sideBox1'>
          <h2>The Blogger</h2>
          <p>This is your side bar. You can add your information or links here.</p>
     </aside>
 
     <div class='clearb'></div>
     
     <footer>
          <p>Copyright 2013 - Game Note</p>
     </footer>
 
</body>
</html>

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!
[purchase_link id="12479" text="Download Now" style="button" color="green"]

Some screenshots of our output:

Page header smartphone screenshot – landscape mode
Page header smartphone screenshot – landscape mode
Footer screenshot from my smartphone in landscape mode.
Footer screenshot from my smartphone in landscape mode.
Header screenshot from my smartphone  in portrait mode.
Header screenshot from my smartphone
in portrait mode.
Body section screenshot from my Smartphone in  portrait mode.
Body section screenshot from
my Smartphone in portrait mode.
Footer screenshot from  my smartphone in portrait mode.
Footer screenshot from
my smartphone in portrait mode.
Screenshot from my 10.1 Android tablet in portrait mode.
Screenshot from my 10.1 Android tablet in portrait mode.

Credits: Image from Game Note.

JavaScript Array CRUD Example

Our code for today will give us example on how to Create, Read, Update and Delete (CRUD) items in a JavaScript array. This technique will give you full control over the fields and values of each array item.

Example use of this code is when you have long rows of input elements and wanted to detect only the elements with inputted values, get their id, value and other related information. You won"t have to loop through all the input elements to check if there are inputted values.

This is because, you can instantly add an item to the array if the value was inputted, edit it when the value were changed, delete it when the value were removed and then read it for posting or later use. We can achieve better performance. Here is a video demo:

JavaScript Crud Example

Our index.php code – here you can see the our JavaScript CRUD functions (with some jQuery help) and sample HTML.

<html>
    <head>
        <title>JS Array CRUD - https://codeofaninja.com</title>
    </head>
    
<body>
 
<!–
    -example row of items
    -id is the item number
    -common class name
–>
Item 1 <input type="text" id="1" class="item" /><br />
Item 2 <input type="text" id="2" class="item" /><br />
Item 3 <input type="text" id="3" class="item" /><br />
Item 4 <input type="text" id="4" class="item" /><br />
Item 5 <input type="text" id="5" class="item" /><br />
 
<br />
<br />
 
<!– display the operations here –>
<b>Actions:</b>
<div id="status"></div>
 
<br />
 
<!– display the array length and items –>
<b>All Items:</b>
<div id="results"></div>
 
</body>
</html>

Now, put the following code before the closing body tag of our HTML code above.

<!– include the jquery –>
<script type="text/javascript" src="jquery.min.js"></script>
 
<script type="text/javascript">
    // initialize array as global variable
    var items = [];
    
    $(document).ready(function(){
    
        //we use the jquery blur event
        $(".item").blur(function(){
        
            //in this example, the item id is the id attribute of the element
            var item_id = $(this).attr("id");
            
            //item value is the inputtedvalue
            var item_value = $(this).val();
            
            //then process the item
            process_item(item_id,item_value);
        });
        
    });
    
    // ———— functions [START] ————
 
    // process item, usually based in item id
    function process_item(item_id,item_value){
        
        if(item_value==""){
            //if item value is empty, delete from the array
            delete_item(item_id);
        }else if(checkIfExists(item_id)){
            //search if item_id exists in the array
            //if item exists, edit it
            edit(item_id,item_value);
        }else if(!checkIfExists(item_id)){
            //if item does not exist, add it
            add(item_id,item_value);
        }
        
        //read the items
        showAllItems();
    }
    
    // ADD
    function add(item_id,item_value){
        items.push({
            "item_id" : item_id,
            "item_value" : item_value
        });
        $("#status").text("Successfully added.");
    }
 
    // EDIT
    function edit(item_id,item_value){
        
        //delete first
        items.remove("item_id", item_id);
        
        //then add again
        items.push({
            "item_id" : item_id,
            "item_value" : item_value
        });
        $("#status").text("successfully edited.");
            
    }
    
    // DELETE
    function delete_item(item_id){
        items.remove("item_id", item_id);
        $("#status").text("Successfully deleted.");
    }
    
    // READ
    function showAllItems(){
        
        //clear results text
        $("#results").text("");
        
        var arr_len = items.length;
        
        // display also the array length
        $("#results").append("Array len: " + arr_len+ "<br />");
        
        //loop through the array to read the items
        for(var x=0; x<arr_len; x++){
            var item_id = items[x]['item_id'];
            var item_value = items[x]['item_value'];
            
            //append to results div to display
            $("#results").append("item_id: " + item_id + " >>> item_value: " + item_value + "<br />");
        }
    }
    
    function checkIfExists(check_item_id){
        
        //get the array length first
        var arr_len = items.length;
        
        //search the array
        //there might be another way
        for(var x=0; x<arr_len; x++){
            var item_id = items[x]['item_id'];
            var item_value = items[x]['item_value'];
            
            if(check_item_id==item_id){
                //it means the item exists
                return true;
            }
        }
        
        return false;
    }
    
    //needs a remove function
    Array.prototype.remove = function(name, value) {
        array = this;
        var rest = $.grep(this, function(item){
            return (item[name] != value);  
        });
 
        array.length = rest.length;
        $.each(rest, function(n, obj) {
            array[n] = obj;
        });
    };
    // ———— functions [END] ————
</script>

Convert to JSON

You can also convert the array to a JSON this way:

Add the json2.js file from here.

<script type="text/javascript" src="json2.js"></script>

…and do this

var json_str= JSON.stringify(items);

Posting the Array

If you want to post the resulting array..

1. Prepare the PHP file that will receive the post value. I created get_post.php with the code:

<?php
//just to display raw values
echo "<pre>";
    print_r($_POST);
echo "</pre>";
 
//access the values
foreach($_POST['items'] as $item){
    echo $item['item_id'] . ":" . $item['item_value'] . "<br />";
}
?>

2. Add a button and a new div area to our index.php

The button:

<input type="button" value="Post Array" id="post" />

Div area where we can see the posted values..

<!– display the posted items value –>
<b>Posted Items:</b>
<div id="postedItems"></div>

3. Clicking the post array button will show the posted value to postedItems div.

$("#post").click(function(){
    $.ajax({
        url: "get_post.php",
        data: {"items": items},
        type: "post",
        success: function(data) {
            $("#postedItems").append(data);
        }
    });
});

The value posted to get_post.php look like this:

Array
(
    [items] => Array
        (
            [0] => Array
                (
                    [item_id] => 1
                    [item_value] => john
                )
 
            [1] => Array
                (
                    [item_id] => 3
                    [item_value] => michael
                )
 
        )
 
)

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!
[purchase_link id="12448" text="Download Now" style="button" color="green"]

Thank you for learning from our post about: JavaScript CRUD example!