emGee Software Solutions Custom Database Applications

Share this

Web Design

Learning Elm From A Drum Sequencer (Part 1)

Smashing Magazine - Thu, 01/11/2018 - 05:00
If you’re a front-end developer following the evolution of single page applications (SPA), it’s likely you’ve heard of Elm, the functional language that inspired Redux. If you haven’t, it’s a compile-to-JavaScript language comparable with SPA projects like React, Angular, and Vue. Like those, it manages state changes through its virtual dom aiming to make the code more maintainable and performant. It focuses on developer happiness, high-quality tooling, and simple, repeatable patterns.
Categories: Web Design

How to Download Files in Python

Tuts+ Code - Web Development - Thu, 01/11/2018 - 04:00

Python provides several ways to download files from the internet. This can be done over HTTP using the urllib package or the requests library. This tutorial will discuss how to use these libraries to download files from URLs using Python.


The requests library is one of the most popular libraries in Python. Requests allow you to send  HTTP/1.1 requests without the need to manually add query strings to your URLs, or form-encode your POST data.

With the requests library, you can perform a lot of functions including:

  • adding form data,
  • adding multipart files,
  • and accessing the response data of Python

The first you need to do is to install the library and it's as simple as:

pip install requests

To test if the installation has been successful, you can do a very easy test in your  python interpreter by simply typing:

import requests

If the installation has been successful, there will be no errors.

HTTP requests include:

  • GET
  • POST
  • PUT
  • HEAD
Making a GET request

Making requests is very easy as illustrated below.

import requests req = requests.get(“http://www.google.com”)

The above command will get the google web page and store the information in thereq variable. We can then go on to get other attributes as well.

For instance, to know if fetching the google web page was successful, we will query the status_code.

import requests req = requests.get(“http://www.google.com") req.status_code 200 # 200 means a successful request

What if we want to find out the encoding type of the Google web page?

req.encoding ISO-8859–1

You might also want to know the contents of the response.


This is just a truncated content of the response.

'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en "><head><meta content="Search the world\'s information, including webpages, imag es, videos and more. Google has many special features to help you find exactly w hat you\'re looking for." name="description"><meta content="noodp" name="robots" ><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta conten t="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image "><title>Google</title><script>(function(){window.google={kEI:\'_Oq7WZT-LIf28QWvMaking a POST Request

In simple terms, a POST request used to create or update data. This is especially used in the submission of forms.

Let's assume you have a registration form that takes an email address and password as input data, when you click on the submit button for registration, the post request will be as shown below.

data = {"email":"info@tutsplus.com", "password":"12345") req = requests.post(“http://www.google.com, params = data)Making a PUT Request

A PUT request is similar to a POST request. Its used to update data.For instance, the API below shows how to do a PUT request.

data= {"name":"tutsplus", "telephone":"12345") r.put("http://www.contact.com, params= data")Making a DELETE Request

A DELETE request, like the name suggests, is used to delete data. Below is an example of a DELETE request

data= {'name':'Tutsplus'} url = "https://www.contact.com/api/") response = requests.delete(url, params= data) urllib Package

urllib is a package that collects several modules for working with URLs namely:

urllib.request  offers a very simple interface, in the form of the urlopen function capable of fetching URLs using a variety of different protocols. It also offers a slightly more complex interface for handling basic authentication, cookies, proxies e.t. c.

How to Fetch URLs With urllib

The simplest way to use urllib.request is as follows:

import urllib.request with urllib.request.urlopen('http://python.org/') as response: html = response.read()

If you wish to retrieve an internet resource and store it, you can do so via the urlretrieve() function.

import urllib.request filename, headers = urllib.request.urlretrieve('http://python.org/') html = open(filename) Downloading Images With Python

In this example, we want to download the image available on this link using both the request llibrary and urllib module. 

url = 'https://www.python.org/static/opengraph-icon-200x200.png' # downloading with urllib # imported the urllib library import urllib # Copy a network object to a local file urllib.urlretrieve(url, "python.png") # downloading with requests # import the requests library import requests # download the url contents in binary format r = requests.get(url) # open method to open a file on your system and write the contents with open("python1.png", "wb") as code: code.write(r.content) Download PDF Files With Python

In this example, we will download a pdf about google trends from this link.

url = 'https://static.googleusercontent.com/media/www.google.com/en//googleblogs/pdfs/google_predicting_the_present.pdf' # downloading with urllib # import the urllib package import urllib # Copy a network object to a local file urllib.urlretrieve(url, "tutorial.pdf") # downloading with requests # import the requests library import requests # download the file contents in binary format r = requests.get(url) # open method to open a file on your system and write the contents with open("tutorial1.pdf", "wb") as code: code.write(r.content) Download Zip Files With Python

In this example, we are going to download the contents of a GitHub repository found in this link and store the file locally.

url = 'https://codeload.github.com/fogleman/Minecraft/zip/master' # downloading with requests # import the requests library import requests # download the file contents in binary format r = requests.get(url) # open method to open a file on your system and write the contents with open("minemaster1.zip", "wb") as code: code.write(r.content) # downloading with urllib # import the urllib library import urllib # Copy a network object to a local file urllib.urlretrieve(url, "minemaster.zip") Download Videos With Python

In this example, we want to download  the video lecture available on this page

url = 'https://www.youtube.com/watch?v=aDwCCUfNFug' video_name = url.split('/')[-1] # using requests # imported the requests library import requests print "Downloading file:%s" % video_name # download the url contents in binary format r = requests.get(url) # open method to open a file on your system and write the contents with open('tutorial.mp4', 'wb') as f: f.write(r.content) # using urllib # imported the urllib library import urllib print "Downloading file:%s" % video_name # Copy a network object to a local file urllib.urlretrieve(url, "tutorial2.mp4") Conclusion

This tutorial has covered the most commonly used methods to download files as well as the most common file formats. Even though you will write less code  when using  the urllib module, the requests module is preferred due to its simplicity, popularity and a wide array of features including:

  • Keep-Alive & Connection Pooling
  • International Domains and URLs
  • Sessions with Cookie Persistence
  • Browser-style SSL Verification
  • Automatic Content Decoding
  • Basic/Digest Authentication
  • Elegant Key/Value Cookies
  • Automatic Decompression
  • Unicode Response Bodies
  • HTTP(S) Proxy Support
  • Multipart File Uploads
  • Streaming Downloads
  • Connection Timeouts
  • Chunked Requests
  • .netrc Support

Categories: Web Design

Captivate Your Audience With These Digital Marketing Tips

Webitect - Wed, 01/10/2018 - 06:03

When you write a blog, your goal is to gain as many subscribers as possible by increasing traffic to your site. Whether you’re a blogger who’s been in the business for many years or are just getting started with your first site, you can probably benefit from some tips to make your blog engaging and attractive to readers. Here are some tips you can implement into your site to gain traffic and hopefully increase your subscriber list. Use Quality Images One of the easiest ways to attract people and make your blog interesting to readers is to include a variety

The post Captivate Your Audience With These Digital Marketing Tips appeared first on Clayton Johnson SEO.

Categories: Web Design

Designing Friction For A Better User Experience

Smashing Magazine - Wed, 01/10/2018 - 05:24
In experience design, friction is anything that prevents users from accomplishing their goals or getting things done. It’s the newsletter signup overlay covering the actual content, the difficult wording on a landing page, or the needless optional questions in a checkout flow. It’s the opposite of intuitive and effortless, the opposite of “Don’t make me think.” Having said that, friction can still be a good thing sometimes. In game design, for example, friction is actually required.
Categories: Web Design

Real-world data in PageSpeed Insights

Google Webmaster Central Blog - Wed, 01/10/2018 - 00:08

PageSpeed Insights provides information about how well a page adheres to a set of best practices. In the past, these recommendations were presented without the context of how fast the page performed in the real world, which made it hard to understand when it was appropriate to apply these optimizations. Today, we’re announcing that PageSpeed Insights will use data from the Chrome User Experience Report to make better recommendations for developers and the optimization score has been tuned to be more aligned with the real-world data.

The PSI report now has several different elements:

  • The Speed score categorizes a page as being Fast, Average, or Slow. This is determined by looking at the median value of two metrics: First Contentful Paint (FCP) and DOM Content Loaded (DCL). If both metrics are in the top one-third of their category, the page is considered fast.
  • The Optimization score categorizes a page as being Good, Medium, or Low by estimating its performance headroom. The calculation assumes that a developer wants to keep the same appearance and functionality of the page.
  • The Page Load Distributions section presents how this page’s FCP and DCL events are distributed in the data set. These events are categorized as Fast (top third), Average (middle third), and Slow (bottom third) by comparing to all events in the Chrome User Experience Report.
  • The Page Stats section describes the round trips required to load the page’s render-blocking resources, the total bytes used by the page, and how it compares to the median number of round trips and bytes used in the dataset. It can indicate if the page might be faster if the developer modifies the appearance and functionality of the page.
  • Optimization Suggestions is a list of best practices that could be applied to this page. If the page is fast, these suggestions are hidden by default, as the page is already in the top third of all pages in the data set.

For more details on these changes, see About PageSpeed Insights. As always, if you have any questions or feedback, please visit our forums and please remember to include the URL that is being evaluated.

Posted by Mushan Yang (杨沐杉) and Xiangyu Luo (罗翔宇), Software Engineers
Categories: Web Design

Visual Studio Code Can Do That?

Smashing Magazine - Tue, 01/09/2018 - 05:55
About two years ago, I begrudgingly opened Visual Studio Code (VS Code) for the first time. The only reason I even did so is that I was working on a TypeScript project (also quite begrudgingly) and I was tired of fighting with the editor and the compiler and all of the settings that I needed to make a TypeScript project work. Someone mentioned to me that TypeScript “just works” in VS Code and I was pleasantly surprised to find that they were right.
Categories: Web Design

Introducing the new Search Console

Google Webmaster Central Blog - Mon, 01/08/2018 - 10:58

A few months ago we released a beta version of a new Search Console experience to a limited number of users. We are now starting to release this beta version to all users of Search Console, so that everyone can explore this simplified process of optimizing a website's presence on Google Search. The functionality will include Search performance, Index Coverage, AMP status, and Job posting reports. We will send a message once your site is ready in the new Search Console.

We started by adding some of the most popular functionality in the new Search Console (which can now be used in your day-to-day flow of addressing these topics). We are not done yet, so over the course of the year the new Search Console (beta) will continue to add functionality from the classic Search Console. Until the new Search Console is complete, both versions will live side-by-side and will be easily interconnected via links in the navigation bar, so you can use both.

The new Search Console was rebuilt from the ground up by surfacing the most actionable insights and creating an interaction model which guides you through the process of fixing any pending issues. We’ve also added ability to share reports within your own organization in order to simplify internal collaboration.

Search Performance: with 16 months of data!

If you've been a fan of Search Analytics, you'll love the new Search Performance report. Over the years, users have been consistent in asking us for more data in Search Analytics. With the new report, you'll have 16 months of data, to make analyzing longer-term trends easier and enable year-over-year comparisons. In the near future, this data will also be available via the Search Console API.

Index Coverage: a comprehensive view on Google's indexing

The updated Index Coverage report gives you insight into the indexing of URLs from your website. It shows correctly indexed URLs, warnings about potential issues, and reasons why Google isn't indexing some URLs. The report is built on our new Issue tracking functionality that alerts you when new issues are detected and helps you monitor their fix.

So how does that work?

  1. When you drill down into a specific issue you will see a sample of URLs from your site. Clicking on error URLs brings up the page details with links to diagnostic-tools that help you understand what is the source of the problem.
  2. Fixing Search issues often involves multiple teams within a company. Giving the right people access to information about the current status, or about issues that have come up there, is critical to improving an implementation quickly. Now, within most reports in the new Search Console, you can do that with the share button on top of the report which will create a shareable link to the report. Once things are resolved, you can disable sharing just as easily.
  3. The new Search Console can also help you confirm that you've resolved an issue, and help us to update our index accordingly. To do this, select a flagged issue, and click validate fix. Google will then crawl and reprocess the affected URLs with a higher priority, helping your site to get back on track faster than ever.
  4. The Index Coverage report works best for sites that submit sitemap files. Sitemap files are a great way to let search engines know about new and updated URLs. Once you've submitted a sitemap file, you can now use the sitemap filter over the Index Coverage data, so that you're able to focus on an exact list of URLs.
Search Enhancements: improve your AMP and Job Postings pages

The new Search Console is also aimed at helping you implement Search Enhancements such as AMP and Job Postings (more to come). These reports provide details into the specific errors and warnings that Google identified for these topics. In addition to the functionally described in the index coverage report, we augmented the reports with two extra features:

  • The first feature is aimed at providing faster feedback in the process of fixing an issue. This is achieved by running several instantaneous tests once you click the validate fix button. If your pages don’t pass this test we provide you with an immediate notification, otherwise we go ahead and reprocess the rest of the affected pages.
  • The second new feature is aimed at providing positive feedback during the fix process by expanding the validation log with a list of URLs that were identified as fixed (in addition to URLs that failed the validation or might still be pending).

Similar to the AMP report, the new Search Console provides a Job postings report. If you have jobs listings on your website, you may be eligible to have those shown directly through Google for Jobs (currently only available in certain locations).

Feedback welcome

We couldn’t have gotten so far without the ongoing feedback from our diligent trusted testers (we plan to share more on how their feedback helped us dramatically improve Search Console). However, your continued feedback is critical for us: if there's something you find confusing or wrong, or if there's something you really like, please let us know through the feedback feature in the sidebar. Also note that the mobile experience in the new Search Console is still a work in progress.

We want to end this blog sharing an encouraging response we got from a user who has been testing the new Search Console recently:

"The UX of new Search Console is clean and well laid out, everything is where we expect it to be. I can even kick-off validation of my fixes and get email notifications with the result. It’s been a massive help in fixing up some pesky AMP errors and warnings that were affecting pages on our site. On top of all this, the Search Analytics report now extends to 16 months of data which is a total game changer for us" - Noah Szubski, Chief Product Officer, DailyMail.com

Are there any other tools that would make your life as a webmaster easier? Let us know in the comments here, and feel free to jump into our webmaster help forums to discuss your ideas with others!

Posted by John Mueller, Ofir Roval and Hillel Maoz
Categories: Web Design

Ghost Button Design: Is This Really Still A Thing (And Why)?

Smashing Magazine - Mon, 01/08/2018 - 06:17
For such a small design element, buttons sure are a complicated one to tackle. It makes sense, what with call-to-action buttons serving as the next step in your visitors’ path to conversion. Mess that up and you might as well say “bye-bye” to business. Though we have a good understanding of the types of button design rules that universally work, there will be times when you’re surprised by a rogue element that performs well.
Categories: Web Design

10 Best WordPress Star Rating Plugins

Tuts+ Code - Web Development - Mon, 01/08/2018 - 04:00

The power of the star.

Not one. Not two. How about five?

That'd be great.

The five-star rating system is one that says so much, so quickly. Browsing movies, products, comments? No matter. A quick glance at a rating is a great way to communicate.

So why not add it to your blog comments, digital downloads, product sales, or media reviews?

You can easily add a WordPress star rating plugin to your website—no matter what you're interested in allowing users to rate.

Dive into these 10 best WordPress star rating plugins and see if you can find your five-star solution.

1. Product Category Rating

Easily boast about your five-star reviews using widgets and shortcodes with the Product Category Rating plugin.

The widget is an easy drag and drop with filters, and shortcodes can easily be configured using the built-in shortcode generator.

"The average rating of the product category is calculated based on each review rating received by the product."

Features also include:

  • custom post type and multisite support
  • support and detailed documentation
  • translation ready
  • and more

Between the easy shortcode generator and built-in widgets, you can easily add WordPress star ratings to your website with the Product Category Rating plugin.

2. Rating Form

If customization is your thing, then look no further for your WordPress star rating plugin—give Rating Form a try.

"Choose or create a Rating Form, choice of Stars, Hearts, Smileys, Thumbs Up & Down and many more or upload your own shapes. Lots of features and still expanding."

Transform those five-star rating reviews into something that matches your website perfectly and jumps off the page. Choose to: 

  • upload your own image
  • change the colors
  • size
  • the list goes on

But visual options are just the beginning.

Rating Form includes all the options you want in a WordPress star rating plugin—and more!

3. Five-Star Ratings & Reviews - WP Rating Plugin for Blogs, Review Sites and E-Commerce Shops

From blog comments to full-featured eCommerce websites, the Five-Star Ratings & Reviews - WP Rating Plugin for Blogs, Review Sites and E-Commerce Shops lets website users rate and review just about any kind of website content.

This WordPress star rating plugin supports:

  • Easy Digital Downloads
  • WP eCommerce
  • WooCommerce
  • and more!

Easily customize your rating icons and enjoy great features like:

  • allowing 1 person to vote based on IP address
  • online shop or marketplace integration
  • Custom Post Type support
  • and more

The Five-Star Ratings & Reviews - WP Rating Plugin for Blogs, Review Sites and E-Commerce Shops plugin is... five stars.

4. WordPress Rate Everything Star Rating Plugin

When five stars aren't enough, you need the WordPress Rate Everything Star Rating Plugin.

Not only does this WordPress star rating plugin work with WooCommerce, it works with any WordPress post, post type, and page. You can even drop it in using a short-code or add it directly to your theme.

Features include:

  • customize the number of stars
  • list in grid/list view and detailed view
  • integrate into all post types or only those specified
  • a different number of stars can be displayed based on display view
  • and more

One of the best features is the vote count system, allowing logged-in users to use AJAX. This makes WordPress Rate Everything Star Rating Plugin a "simple yet powerful rating solution with industry-leading accuracy in displaying decimal ratings."

5. Sama Author Review WordPress Plugin

The Sama Author Review WordPress Plugin is one of the more noteworthy designs in the WordPress star rating plugin space.

Features include:

  • allowing any user to leave a rating or only those logged in
  • supports Schema for Google Rich Snippet
  • three custom widgets and WPML support

And includes three different styles:

  1. Stars
  2. Points
  3. Percentages

With its unique design, the Sama Author Review WordPress Plugin is worth your attention.

6. WooCommerce Product Star Rating and Review

This is a WordPress star rating plugin made for WooCommerce. The WooCommerce Product Star Rating and Review makes it super easy to allow shoppers to leave reviews for your products—but only products that have been purchased by the customer.

"WooCommerce Product Star Rating and Review plugin is built to encourage customers to add lovely star ratings & reviews to your products, and make it extremely easy to do so."

Using the WooCommerce Product Star Rating and Review plugin adds features that customers would expect to find on big eCommerce sites.

7. Contact Form 7 Star Rating Field

Here's the perfect WordPress star rating plugin for those of you using Contact Form 7.

The Contact Form 7 Star Rating Field brings 12 different rating styles to the Star Rating field for one of the most popular contact forms for WordPress.

Like other Contact Form 7 fields, you have the option to set up your star rating to be required or not. You can use shortcodes to include the rating result in email, set a default rating, and much, much more.

Check it out. The Contact Form 7 Star Rating Field is a solid option.

8. Gravity Forms Star Rating Field

Easily add a star rating (or thumbs up, hearts, smiley faces, etc.) to your Gravity Form with the Gravity Forms Star Rating Field.

"Choose from 14 different rating style and set some setting options for your rating field."

Features include:

  • customize and show current rating on hover
  • customize and show rating text on the tooltip
  • and more

If you're using Gravity Forms, you'll want to use the Gravity Forms Star Rating Field.

9. Ninja Forms - Unique Fields

The Ninja Forms solution for a star rating is far more robust than any other listed thus far, when using the Ninja Forms - Unique Fields.

While it includes a star rating, it includes many other unique fields.

Additional unique fields include:

  • select, number
  • email, phone, date
  • address, city, zip, state, country
  • and more

And each field gets uniqueness settings, frontend validation, and more.

The Ninja Forms - Unique Fields is a must-have for any Ninja Forms user.

10. User Rating / Review Add on for UserPro

The User Rating / Review Add on for UserPro is a special WordPress star rating plugin specifically built for UserPro—a user profile and community plugin.

Features include:

  • ability to rate both users using star ratings or using text comments
  • adjust rating restrictions based on user role
  • shortcode and translation support
  • and more

Easily add star ratings to your UserPro community with the User Rating / Review Add on for UserPro plugin.


The Envato Market offers a great variety of WordPress themes and WordPress plugins, and their five-star star WordPress star rating plugins do not disappoint.

Adding the power of star ratings to your eCommerce site, digital downloads, contact forms, and comment sections has never been so easy.

If you still haven't found exactly what you're looking for, you'll want to check out Envato Tuts+. They have excellent WordPress tutorials, eBooks, and courses. You might try the WordPress Plugin Development Essentials or maybe the WordPress Hacker's Guide to the Galaxy. If you prefer eBooks, then Useful Tricks and Techniques for WordPress and Mastering WordPress are options you'll want to look at.

Categories: Web Design

Why do People Hate Papyrus and Comic Sans?

The world we live in is a mix of opinions and it’s hard to definitively agree on anything. But one thing’s for sure—Comic Sans and Papyrus are the worst....

The post Why do People Hate Papyrus and Comic Sans? appeared first on Onextrapixel.

Categories: Web Design

SEO Methods to Double-down on in 2018

Webitect - Sun, 01/07/2018 - 11:25

The necessity of using search engine optimization to improve Google organic ranking results is ever present. If you’re not building new links to your site at a record-setting pace, your competitors surely are. In the race to improve results, higher-quality and a greater number of links than before are required to get better results when going up against big media companies that rank effortlessly because Google favors big over better. Royalty Free Photo Here are a handful of SEO methods that you either need to re-double your efforts on or try out for the first time in the SEO campaigns

The post SEO Methods to Double-down on in 2018 appeared first on Clayton Johnson SEO.

Categories: Web Design

Dwelling On The Past: The Importance Of Self Reflection (Part 2)

Smashing Magazine - Fri, 01/05/2018 - 07:06
Current and aspiring web professionals must continually grow in order to stay relevant. Our field doesn’t allow for stagnation. In part one of this series, I discussed the importance of project retrospectives in facilitating and documenting team growth. We don’t always have the luxury of engaging in team retrospectives, or even of working on teams. Personal reflection provides similar benefits, while focusing on your individual experiences. Personal reflection enables us to process and make meaning of all of the great (and not so great) learning and working experiences we’ve had.
Categories: Web Design

The Rise Of The State Machines

Smashing Magazine - Thu, 01/04/2018 - 05:05
It’s 2018 already, and countless front-end developers are still leading a battle against complexity and immobility. Month after month, they've searched for the holy grail: a bug-free application architecture that will help them deliver quickly and with high quality. I am one of those developers, and I’ve found something interesting that might help. We have taken a good step forward with tools such as React and Redux. However, they’re not enough on their own in large-scale applications.
Categories: Web Design

8 of the Best Event Themes for WordPress

WordPress is a powerful content management system that lets you build just about any kind of website – including event sites. And it’s all made possible due to the sheer...

The post 8 of the Best Event Themes for WordPress appeared first on Onextrapixel.

Categories: Web Design

Front-End Performance Checklist 2018 [PDF, Apple Pages]

Smashing Magazine - Wed, 01/03/2018 - 08:03
Performance matters — we all know it. However, do we actually always know what our performance bottlenecks exactly are? Is it expensive JavaScript, slow web font delivery, heavy images, or sluggish rendering? Is it worth exploring tree-shaking, scope hoisting, code-splitting, and all the fancy loading patterns with intersection observer, clients hints, CSS containment, HTTP/2 and service workers? And, most importantly, where do we even start improving performance and how do we establish a performance culture long-term?
Categories: Web Design

The Front-End Performance Challenge: Winner And Results

Smashing Magazine - Wed, 01/03/2018 - 07:15
A few weeks ago, we asked our readers and the community to use everything they could to make their websites and projects perform blazingly fast. Today, we’re thrilled to show off the results of this challenge and announce the winner who will be awarded with some smashing prizes indeed! What prizes, you ask? The winner wins a roundtrip flight to London, full accommodation in a fancy hotel, a ticket to SmashingConf London 2018, and last but not least, a Smashing workshop of their choice.
Categories: Web Design

Introducing Web Payments: Easier Online Purchases With The Payment Request API

Smashing Magazine - Tue, 01/02/2018 - 04:52
Buying things online can be a frustrating process, especially on mobile. Even if the pages are well designed, there’s a lot of information required: Our contact information, shipping and billing addresses, shipping option and card details. If you’ve ever just given up sometimes, you’re in the majority. The Baymard Institute took an average across 37 different studies and found that 69% of shopping carts are abandoned. A typical, long checkout form on mobile.
Categories: Web Design

Handling Forms in Vue.js

Tuts+ Code - Web Development - Tue, 01/02/2018 - 04:00

When building web applications, there is always the possibility of working with forms. Learning to handle them as you work with different tools is very important. In this tutorial, you will see how to handle forms in Vue.js.

Get Started

Create a new Vue project using Vue-CLI. If you do not have Vue-CLI installed on your machine, you can do so by running:

npm install -g vue-cli

That will install Vue-CLI globally on your machine. You can go ahead to create the project by running:

vue init webpack vue-forms

That will create a new Vue project, using the Webpack template. Navigate to the directory that was created for the project, and install the dependencies.

cd vue-forms npm install

You will be making use of Bootstrap in this tutorial. Open your index.html file and make it look like this.

#index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>vue-forms</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"></head> <body> <div id="app"> </div> <script src="/dist/build.js"></script> </body> </html>

Nothing fancy here—just the link element tag for our Bootstrap stylesheet. You will build a simple registration form from scratch, and bind the values entered into the form using v-model. When working with forms in Vue.js, you bind form input values to the Vue instance using the v-model directive.

Input Binding

Let's get started with some simple text input to collect the email address, password, and age of the user. Open up your App.vue file.

Edit the template section to look like what I have below.

#src/App.vue <template> <div class="container"> <form> <div class="row"> <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3"> <h1>Enter your information</h1> <hr> <div class="form-group"> <label for="email">Mail</label> <input type="text" id="email" class="form-control" v-model="userData.email"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" id="password" class="form-control" v-model="userData.password"> </div> <div class="form-group"> <label for="age">Age</label> <input type="number" id="age" class="form-control" v-model="userData.age"> </div> </div> </div> </form> </div> </template>

In the above, you are using the v-model directive to bind the inputs for email, password, and age to an object. Here, the object is called userData. The userData object is supposed to have different properties—email, password and age—where the values of the inputs will be saved.

The userData object has to be defined in the data option of your Vue instance.

<script> export default { data () { return { userData: { email: '', password: '', age: 40 } } } } </script>

With that, you have established a two-way binding. You can now access the values for the email, password, and age inputs as userData.email, userData.password, and userData.age respectively. From the above, you set the default value for the age object. Without entering a value, the value is set at 40. This is an example of how you can implement defaults when working with forms in Vue.js.

Input Modifiers

Now go to the form group for your password to make the password visible. The form group should look like this.

<div class="form-group"> <label for="password">Password</label> <input type="password" id="password" class="form-control" v-model="userData.password"> <p>{{ userData.password }}</p> </div>

As you enter inputs in the input box, each letter you enter gets displayed. Vue.js gives you the option to halt display of the values till you move to another input field or another place in the page. To do this, you have to edit the v-model directive by adding a lazy modifier, like so.

<input type="password" id="password" class="form-control" v-model.lazy="userData.password">

This does not listen to the input event, but the change event that gets fired when you are done with that input field. Another modifier that can come handy is the trim modifier. If used for the email field, it will look like this.

<input type="text" id="email" class="form-control" v-model.trim="userData.email">

This is the same way you used the lazy modifier. The trim modifier will remove any extra space from the entered values.

Working with textarea is like what you did above. The only difference is that interpolation will not work. Let's add a textarea to our form, inside the form tag.

<div class="row"> <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3 form-group"> <label for="message">Message</label><br> <!-- Interpolation between <textarea>{{ test }}</textarea> doesn't work!--> <textarea id="message" rows="5" class="form-control" v-model="message"></textarea> </div> </div>

Update the model to look like this.

<script> export default { data () { return { userData: { email: '', password: '', age: 40 }, message: 'This is a placeholder text' } } } </script>Checkboxes and Radio Buttons

Checkboxes give users the opportunity to select more than one option. When implementing this, the values are bound to the same array.

So, in your template, you should add this.

<div class="row"> <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3"> <div class="form-group"> <label for="designer"> <input type="checkbox" id="designer" value="Designer" v-model="occupation"> Designer </label> <label for="developer"> <input type="checkbox" id="developer" value="developer" v-model="occupation"> Developer </label><!-- Also show for single checkbox with true/ false --> </div> </div> </div>

While the data model is updated too.

data () { return { userData: { email: '', password: '', age: 40 }, message: 'This is a placeholder text', occupation: [] } }

If you are working with radio buttons, where the user can only select one option, you do not make use of an array. Let's add radio buttons to the registration form.

<div class="row"> <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3 form-group"> <label for="male"> <input type="radio" id="male" value="Male" v-model="gender"> Male </label> <label for="female"> <input type="radio" id="female" value="Female" v-model="gender"> Female </label> </div> </div>

The corresponding data model will look like this.

data () { return { userData: { email: '', password: '', age: 40 }, message: 'This is a placeholder text', occupation: [], gender: 'Female } }

Vue.js knows that both radio buttons belong to the same group, so it only allows the selection of one. It also stores the value of the selected radio button in the gender property; this is done automatically for you.

Handling Drop-Downs

The v-model directive is also used for dropdowns. In the template, you are to loop through a collection of values, as these values are automatically populated in your form.

Here is a drop-down that loops through a list; the list will be defined in the data model.

<div class="row"> <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3 from-group"> <label for="expertise">Expertise</label> <select id="expertise" class="form-control" v-model="selectedExpertise"> <option v-for="expertise in expertises">{{ expertise }}</option> </select> </div> </div>

The data model should look like this.

data () { return { userData: { email: '', password: '', age: 40 }, message: 'This is a placeholder text', occupation: [], gender: 'Female, selectedExpertise: 'Professional', expertises: ['Newbie', 'Beginner', 'Professional', 'Expert'] } }

The binding is done on the select tag element, and not on the individual options. A default option is set in the data model when a user selects another option, and the selectedExpertise gets updated.

Form Submission

Here, you'll add a submit button. You'll need to prevent the submit button from submitting the form to the server, which is its default behaviour. You'll substitute that with displaying the form on the page. 

Thus there will need to be a method that changes the value of the display section to true. When true, the display section is expected to show the values of the form. Start by adding the submit button.

<div class="row"> <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3"> <button class="btn btn-primary" @click.prevent="submitted">Submit!</button> </div> </div>

Here, you're listening for the click event, and when the button gets clicked, you want to call a method. This method needs to be added to the script section of your code.

<script> export default { data () { return { userData: { email: '', password: '', age: 40 }, message: 'This is a placeholder text', occupation: [], gender: 'Female, selectedExpertise: 'Professional', expertises: ['Newbie', 'Beginner', 'Professional', 'Expert'] } }, methods: { submitted() { this.isSubmitted = true; } } } </script>

With that done, you can add the display section, after the closing tag of the form.

<hr> <div class="row" v-if="isSubmitted"> <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-heading"> <h4>Your Data</h4> </div> <div class="panel-body"> <p>Mail: {{ userData.email }} </p> <p>Password: {{ userData.password }}</p> <p>Age: {{ userData.age }}</p> <p style="white-space: pre">Message: {{ message }}</p> <p><strong>Interest</strong></p> <ul> <li v-for="item in interest">{{ item }}</li> </ul> <p>Gender: {{ gender }}</p> <p>Priority: {{ selectedExpertise }}</p> </div> </div> </div> </div>

With that, when the submit button gets clicked, the values entered in the form will be displayed.


At this point, you can work effectively with forms when building applications using Vue.js. If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato Market.

You learned how to work with all possible parts of a form you might encounter in your journey as a developer. You've tried your hand at inputs, select options, radios, checkboxes, and textarea. 

Thanks for reading!

Categories: Web Design

Web Design Trends for 2018 Predict Interesting Changes

Current web design trends forecast exciting changes on the web in the year 2018. We can expect the arrival of a new visual language with bold colors and powerful...

The post Web Design Trends for 2018 Predict Interesting Changes appeared first on Onextrapixel.

Categories: Web Design

Inspiring Desktop Wallpapers To Welcome 2018 (January Edition)

Smashing Magazine - Sun, 12/31/2017 - 03:22
The new year is an opportunity to start over fresh, to overcome routines and rethink processes. And, well, despite all the New Year’s resolutions you might have made, sometimes it’s the small things that work wonders. A tidy desktop and a new, inspiring wallpaper, for example, that caters for a little inspiration shot when you need one. To kick off 2018 with wallpapers that are a bit more distinctive as the usual crowd, artists and designers from across the globe once again challenged their artistic skills and designed unique desktop wallpapers for you to indulge in.
Categories: Web Design