Getting Started 3: HTML – forms and tables

This is the 3rd post in the Getting Started series.

In this post, I will be introducing more HTML elements, mainly the form and table elements.

HTML forms

For forms, the two main attribute are action and method. action tells the form where to submit the values, and method tells the form how to sumbit the form, the value can be either GET (default) or POST. If you have no idea what I am rambling about, read the rest first, then head over to this article to get it all sorted out.

What’s more important here is the form elements. These comprises everything that makes up a form. When rendered, the browser will display the form with the different field, depending on the element used.

Each element will have the tag name and it would correspond to the different fields in the form (eg. ’email’ and ‘password’ for a login form).

input (the fundamental one)

This is the one you probably will use the most often. The input element is usually accompanied by a type tag. For those usual text input that you see on most forms, the type value is text, but there are other types of inputs too, like number and date, just to name a few.

One commonly used input will be the password typed input. Instead of displaying the text, asterixs are used instead to hide the input text from prying eyes.

Most input type will also have the placeHolder attribute. For modern browsers, the placeHolder value will be displayed when the value of the input is empty.

input (the special kind)

There are some special kinds of input too. When the input is typed submit, a button will be rendered to submit the form where the input resides in.

There is also a type hidden for input tags. This tag will not be displayed and is usually used to submit “behind-the-scene” information that users do not need to enter directly.

textarea (the bigger text input)

For form inputs which are longer (eg. addresses, paragraph of text), there is the textarea element. This element allows for multiline text input. For long input, the textarea is usually used.

option (the dropdown list)

In some inputs you only want to give your users a few options (their month of birth for example).

So you make use of option and select to create the dropdown list they can choose from. select is the tag that encloses the different options, in the aptly named tag, option.

radio buttons (choosing between options)

This is another way of allowing your users to choose from different options. When using radio buttons, all the options are shown, as compared to dropdown lists, where the options are revealed only after a click. Radio buttons are displayed when input are typed radio and are activated when the attribute checked exist for the element.

checkbox (either on or off)

For this element, it used for fields where there is only two choices (eg. ‘remember password’ for a login form) — selected or not. A checkbox is displayed when an input is typed checkbox.

HTML5 inputs (specialized pickers)

As I mentioned before, the input tag is the mother of all inputs. In HTML5, there are some new types of inputs that triggers specialized pickers for choosing (eg. colors, dates). There is really too many types to go through throughly here. Visit this article to view the kinds of input available for use.

input (the expansion pack)

Of course, everything is flexible in frontend development. With sufficient knowledge in styling and javascript, almost everything is possible.

Libraries such as AnyPicker and jqueryUI extends the form functionality of existing browsers by providing even more specialized pickers for different form fields. Anyone interested should go and check them out.

sample (basic HTML forms)

<form>
    <input name='input_text' type='text' placeHolder='text input' />
    <input name='input_hidden' type='hidden' value='not_be_shown' />
    <textarea name='input_textarea' placeHolder='textarea'></textarea>

    <select name='input_select'>
        <option>Option 1</option>
        <option>Option 2</option>
    </select>

    <div class="'radio'">
        <div>
             Option 1
        </div>
        <div>     
            Option 2
        </div>
    </div>

    <div>

        Yes or No
    </div>

    <input type='submit' value='Click Me' />
</form>

rendered:

tables (displaying information)

Most data are displayed in tabular format, it allows the users to quickly see the relation between the different entities and compare data more efficiently.

The tables in HTML are enclosed in the table tags. Within the section, all the information will be formatted by its row and column.

tr & td (basic table elements)

For tables, the most important thing will be the rows and columns. In HTML, the rows are represented using the tr tag and the column, using td tag.

thead and tbody (table styling)

When displaying data, the headings are very important. In HTML, the headings and the data itself is separated using the thead and tbody tags. This way, the headings can be styled separately from the rest of the table.

additional data formatting

Sometimes, tables are not as simple as they seem. In more complex arrangement, a single table cell could span over multiple rows or columns, and this is where colspan and rowspan comes in. Read this article to have a better understand of how to use those attributes.

sample (basic HTML tables)

<table>
    <thead>
        <tr>
            <td>Index</td>
            <td>Name</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>01</td>
            <td>Metta Ong</td>
        </tr>
        <tr>
            <td>02</td>
            <td>Alex Malcolm</td>
        </tr>
    <tbody>
</table>

rendered:

end

Now, here is the end to the third part of the get started tutorial series. In the next few tutorials, you will be working on CSS styling and JavaScript coding.

Advertisements

Getting Started Series

The Getting Started series introduces you to fontend development. Follow these tutorials to learn the basics of web developement. With all these basics, you can make simple adjustments to your sites, add in new information on your own.

  1. Markdown – Simple formatting for documents
  2. HTML – markup language for the web
  3. HTML – forms and tables

But if you want a more complete tutorial, on how to design and implement a website design from scratch, contact ongspxm@gmail.com for more information.

Getting Started 2: html – markup language for web documents

This is the 2nd post in the Getting Started series.

Basic HTML

HTML(hyper text markup language) is a data representation format based on XML. It is used for formatting web documents in general, and contain all the required elements for a browser to render the tags as a website.

Basic XML

HTML(or XML in general) follows this following set of formatting and rules.

Sample XML Document (Not HTML btw)

<Document>
    <title>Hello World Page</title>
    <article author="Metta Ong">Lorem Ipsum</article>
</Document>

As seen from above, the document is formed by tags in the form of tags. Tags come in pairs, opening and closing tags. The opening tag is enclosed with a less than and greater than sign, and a closing tag has a / before the tag name.

Attributes are “descriptions” attached to the tags. In the above example, the author="Metta Ong" is the attribute attached to the article tag. Content placed between the open and close tags are actual text content of the tags.

XML hierachy is pretty simple to understand. In the example above, both the title and article tags are considered children of the Document root tag.


Main structure of web pages

<!DOCTYPE HTML>
<html>
    <head>
    </head>
    <body>
    </body>
</html>

Main structure of web document

Different versions of HTML

There are many HTML versions out there (the most recent one is HTML5). To tell the browser which version of HTML your document is, we use the DOCTYPE tag.

So, at the top of your document, incude the following line: “. This tells the browser that your document follows the HTML5 format.

For those curious few out there, there are a few different types of DOCTYPE for HTML4 document is – strict(), transitional(), etc. You can read more about doctypes here.

Main 2 components

The head tag is the place where all the information goes. Data contained in this tag is usually not rendered. By convention, all scripts and styling goes here, together with all the information of the document, like the title, description, etc.

The body tag is the place where all the rendered information go. All your headers, navigation and content goes here.

Document information

<head>
    <title>Title of Document</title>
    <link href='/path/to/stylesheet.css' type='stylesheet' />
</head>

Example head tag

All the information will be stored here, the title of the document, all the metadata (description, author, etc). The metadata can be used for search engine optimization (SEO), it gives the browser detailed information to categorize your document (more on that in other tutorial).

While styling can be done on the main html file itself, you can also attach stylesheets using the link tag. The syntax to do so is as follows: “

You can attach things like favicons (the small tiny logos for your page). Using the link tags, these images can be attached as so:

<!-- linking a style sheet -->
<link href='path/to/style.css' rel='stylesheet' />

<!-- favicon -->
<link href='path/to/icon.png' rel='icon' type='image/png' />

Basic components

In the previous post, you learnt about formatting documents using markdown, know that you know the basics about document formatting, I will now teach you how to do all that in HTML (yeah, finally :>)

Headers

In markdown, there are different kinds of headers, representing different layers of information. The highest level of all headers have the h1 tag, it all goes all the way, from h2, h3, all the way to h6.

<h1>Usually for the main title of the page.</h1>
<h2>Subheadings. Title for the different sections</h2>
<h3>Even smaller headings, content headers maybe?</h3>
<h4>Not too sure why you would go so deep...</h4>
<h5>Probably just use this for styling purposes...</h5>
<h6>When you reach here, its time to split your content...</h6>

Paragraph text

The p tag (yeah, p for paragraph) used to contain all your text. It can be can be any kind of text, its the generic text container. It is to be embedded in the new HTML5 content tags for SEO (searc engine optimization).

Text styling

Within the paragraph tags, there are some special styling tags to basic transformation to yout text. Here are some of the basic tags available for use.

<b>bold, b for bold</b>
<strong>makes the text bold</strong>

<i>italics effect, i for italics</i>
<em>also italics effect, emphasized</em>

<u>underlined text, u for underline</u>

<mark>highlight text. yep, like a highlighter.</mark>

<s>to show cancellalation (strikethrough), really...</s>
<del>strikethough, similar to the 's' tag</del>

<sub>subscript, text written close to the foot of the text</sub>
<sup>superscript, you know like in math, the power function</sup>

<code>Shows code. text will be displayed in monotype font.</code>

For more advanced styling, you can take a look at the CSS declaration specified for text..

Images

Your pages will be boring with any visual candy. The image tags (img) contains your images. (like duh.)

<img src='http://lorempixel.com/400/200/' alt='a random image' />

Yes, img tags are one of those special kinds that do not need to be closed (because your browser most likely wont render anything enclosed by those tags).

Links

The web works like a interwoven collection of pages, and linking them together will be these a tags (a for anchor). These tags have an attribute href (hyperlink reference), which points to the location you want to redirect your readers to. And this is how you use it:

<a href='http://www.google.com' target='_blank'>
    Link to google
    <img src='path/to/img'/>
</a>

Yep, you can put images in your a tags too. Actually, you can put in anything basic tags under the sun and it will work.


Adding more structure

Most pages will have a certain page structure to it, header,content, footer, at least. The basic containers for most elements are the div and span tags.

But in html5, there are many more tags that can better segmentalized your page into the appropriate sections.

Basic containers

The most basic tags are the div and span. There are a few difference between them. div is for block elements and span is for inline elements.

Block elements refers to a whole section of the page which are displayed as blocks of content. These usually refer to section of the page, such as header, navigation bar or footer.

Inline elements as their names suggest, refers to a small portion of content, within a block to which specialized styling (usually through CSS) is applied to.

HTML5 section tags

In HTML5, there are much more section tags that helps add structure to the documents.

header is a section tag for containing the header content. It can include your logo, your page header, and whatever you plan on putting in your header section.

footer serves the same function as the header tag, a container for footer content (including copyright and contact information).

article contains the main content for the document. But if they are sections in the article, you can use the section tag to separate your content.

nav tags are for navigation. It will consist the links to the different sections of your website (home, about, etc).

aside tags are for sidebars which contain additional bits of information (description for blogs for example).

There are more of course, you can view all that here.


Special Content

In HTML5, there are many new semantics tags added to give structure to your documents.

Pre VS Code

We talk about the code tag just now. But for whole sections of codes, we use the pre tag to contain whole sections of code, preserving the newlines and whitespaces, keeping all the indentation intact.

<pre>
function add(x, y){
    return x+y;
}
</pre>

Figure

The figure tag is used to contain illustrations and pictures. The figcaption is used to add description to the figure. This all is written in the following manner:

<figure>
    <img src='http://lorempixel.com/400/200/' />
    <figcaption>
        Some random picture from lorempixel
    </figcaption>
</figure>

Audio

The audio tag is used to embed an audio resource into the page.

<audio src='test.mp3' type='audio/mpeg' />

Video

video tag is similar to audio tag, but with videos instead of audio files.

Canvas & SVG

The canvas and svg tags are used for drawing things on the page. The canvas tag is controlled using javascript. The svg tag draws using xml. Learn more about canvas and svg.


What’s next

  • Forms (text input, form submission)
  • Tables (systematic display of info)
  • Separators (line breaks)

Design Mockup – GeissDice from 99designs

Another mockup from 99designs. This layout consist of a few intricate design elements, with the logos changing on mouseover.

This was done after a long time of rest. After I entered, my development process have not progressed far. This particular mockup took abit longer to complete, around 3 to 4 hours for this piece of work, but it turned out to look very good indeed.

Original design:
GeissDice from 99designs

Design Mockup – Etched from 99 designs

Other design from 99designs. This is particularly modern, using a simple color scheme of only a few colors, relying on the subtle changes on the grayscale to distinguish the different sections of the design.

There are many subtle designs in this one, but there are some elements that are fairly hard to extract (the background for the display). There is not much differences in there overall, check out the the completed mockup here.

Original design::
Etched by WebBox

Tutorial – Creating a webchat with web.py

BitBucket Repository

I have previously written a tutorial on how to do long polling on webpy framework. Well, this is an updated version with a code repository that you can use to include an webchat subapp in your webpy applications.

Tools required

Frontend implementation – Layouts

For the main page, it would consist of one main area where the messages will be displayed. And an area at the bottom which consist of a type input, where the messages are submitted.

All the javascript coding will be included in the webchat.js, which will be described in more detail later.

/static/layout/index.html:

$def with (msgs)
<script src="static/js/jquery-1.11.1.min.js"></script><script src="static/js/webchat.js"></script>
<div id="msgs">
<h1>Messages</h1>
$for msg in msgs:
<div class="msg">$msg</div>
</div>
<div id="entry"><input id="message" type="text" placeholder="Message here ..." />
<input type="submit" value="submit" /></div>

The styling is not so important for this project, but you can view the CSS style in the code repository.

Storing the messages

We will be using sqlite to store our messages. So, open up your console, and type in sqlite3 database.db, and create the table using the following schema:

CREATE TABLE msgs(
msg_id INTEGER PRIMARY KEY,
msg_content TEXT NOT NULL
);

Simulating real-time events – Client side

To simplify our lives, we will be using jquery for the ajax calls. Everytime a call is returned, the message wrapper(#msgs) will be updated and another call is made.

Another function is needed to send the message to the server for storing into the database.

These functions will be included inside /static/js/webchat.js:

function sendMsg(){
var div = $('#message')[0];
var msg = div.value;

if(msg==''){
alert('Message cannot be blank');
}else{
div.value = '';
$.ajax({url:'/send?msg='+msg});
}
}

function longPoll(idx){
$.get(
url='/get?idx='+idx
).done(
function(data){
data = eval('('+data+')');
var msgs = data['msgs'];
if(msgs){
for(var i=0; i<msgs.length; i++){
$('#msgs')[0].innerHTML += "
<div class="msg">"+msgs[i]+"</div>
"
}
}
longPoll(data['idx']);
}
);
}

Simulating real-time events – Server side

Framework for the webpy application

This is the basic framework for webchat.py:

import web, time, json

urls = [
'/', 'Index',
'/send', 'SendMsg',
'/get', 'GetMsg'
]
render = web.template.render('layouts')
app = web.application(urls, globals())
db = web.database(dbn='sqlite', db='database.db')

class Index:
def GET(self):
return

class SendMsg:
def GET(self):
return

class GetMsg:
def GET(self):
return

if __name__ == '__main__':
app.run()

Serving the existing messages

Alter the Index class to read messages from the database and render it inside the layout:

class Index:
def GET(self):
res = db.select('msgs')
msgs = [r for r in res]

content = [m['msg_content'] for m in msgs]
return render.index(content, msgs[-1]['msg_id'])

Add new messages to the database

Insert the content using /send into the database:

class SendMsg:
def GET(self):
i = web.input()
if i.get('msg'):
db.insert('msgs', msg_content=i.get('msg'))
return
else:
return web.notfound()

Getting new messages – Long Polling

This is the important bit. The server side code for the long polling process:

class GetMsg:
def GET(self):
i = web.input().get('idx')
print i
if not i or not i.isdigit(): i = '0'

max_iter = 20; iter = 0
msgs = []
while not len(msgs) and iter'+i)
msgs = [r for r in res]
iter += 1
time.sleep(i)

if len(msgs): i=msgs[-1]['msg_id']

return json.dumps({
'msgs':[m['msg_content'] for m in msgs],
'idx':i
})

A bit of explanation here. The while loop and the time.sleep is what makes the whole idea works. The server will keep the request open until it detects a change in the database.

Running the server – Gevent WSGIServer

If you are running this as a subapp. Here is all you have to know. If you are running it as a standalone application, do read on.

Webpy’s default web server is not that great for production. Instead, we will be using the Gevent WSGIServer to run the application.

from gevent import monkey, pywsgi;
monkey.patch_all();

''' Whatever code you have '''

if __name__ == '__main__':
print 'WSGISever on 8080'
application = app.wsgifunc()
pywsgi.WSGIServer(('', 8080), application).serve_forever()

Fixing the static directory problem

The WSGIServer does not automatically serve static file like webpy. Fortunately, there is a fix for this:

urls = [
'/static/(.*)', 'Static',
'/', 'Index',
'/send', 'SendMsg',
'/get', 'GetMsg'
]

class Static:
def GET(self, file):
try:
f = open('static/'+file, 'rb')
return f.read()
except:
return web.notfound()

Going on from here

If you are lost in any of the steps above, do visit the code repository. It might be helpful to have a working sample where you can follow. Any troubles, drop me an email or leave it in the comments, I will help to be the best of my abilities.

BitBucket Repository