Input Min Max



In the first article in this series we looked at the history of HTML5 forms and many of the new attributes available to us. In this second and final part of the series, we’ll look at the new input types available in HTML5. As we’ll see, these new features will go a long way toward making your life easier while delivering a delightful user experience. The best thing about all this? You can start using them now.

Min dan max merupakan salah satu atribut yang ada di bahasa pemograman HTML. Fungsi dari atribut min dan max adalah memberi batas minimum dan maksimum yang boleh diinputkan. Min dan max digunakan untuk menginput angka, sedangkan pada inputan teks min dan max tidak akan bekerja. Dalam penggunaan atribut min dan max, kita dapat mengatur input. Inputs with type range render using Bootstrap v4's.custom-range class. The track (the background) and thumb (the value) are both styled to appear the same across browsers. Range inputs have implicit values for min and max of 0 and 100 respectively. You may specify new values for those using the min and max props. The maxlength attribute specifies the maximum number of characters allowed in the element. The maximum number of characters (as UTF-16 code units) the user can enter into the text input. This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the text input has no maximum length. This value must also be greater than or equal to the value of minlength.

This is article is an excerpt from Chapter 6 of Beginning HTML5 and CSS3: The Web Evolved by Christopher Murphy, Oli Studholme, Richard Clark and Divya Manian, published by Apress.

Note: As this article is a book excerpt, browser renderings of attributes and input types may have altered since the screenshots were taken. Additionally, browser support may have increased since publication so please refer to the links at the end of the article for the current state of browser support.

New input types

HTML5 introduces no less than a baker’s dozen (yes, that’s 13!) new input types for forms. We’re going to take a brief look at each of them and explain why you should be using them right now. These new input types have dual benefits: using them means less development time and an improved user experience. The new input types we’ll be looking at are:

Input min max html

search

Search seems like an appropriate place to start our foray into HTML5 input types. When we talk about search, we’re not just talking about Google, Bing, or Yahoo. We’re talking about the search field on that e-commerce site you just made a purchase from, on Wikipedia, and even on your personal blog. It’s probably the most common action performed on the Web every day, yet it’s not marked up very semantically, is it? We all tend to write something like this:

Well, what if we could write something like …

With HTML5 we can. Feels much better, doesn’t it? Desktop browsers will render this in a similar way to a standard text field—until you start typing, that is. At this point, a small cross appears on the right side of the field. Notice the x in Figure 1. This lets you quickly clear the field, just like Safari’s built-in search field.

On a mobile device, however, things start to get interesting. Take the example iPhone shown in Figure 2; when you focus on an input using type='search', notice the keyboard, specifically the action button on the keyboard (bottom right). Did you spot that it says “Search” rather than the regular “Go”? It’s a subtle difference that most users won’t even notice, but those who do will afford themselves a wry smile.

As you’ve seen with the new attributes, browsers that don’t understand them will simply degrade gracefully. The same applies to all of the new input types discussed here. If a browser doesn’t understand type='search', it will default to type='text'. This means you’re not losing anything. In fact, you’re using progressive enhancement and helping users to have a better experience. Let’s face it: filling out web forms isn’t very fun, so anything you can add to ensure a smoother experience, the better.

email

In rendering terms, the email input type is no different than a standard text input type and allows for one or more e-mail addresses to be entered. Combined with the required attribute, the browser is then able to look for patterns to ensure a valid e-mail address has been entered. Naturally, this checking is rudimentary, perhaps looking for an @ character or a period (.) and not allowing spaces. Opera 9.5+, Firefox 4+, Internet Explorer 10 and Chrome 5+ have already implemented this basic validation. The browser goes as far as presenting the user with an error message (see Opera in Figure 3) if the e-mail address entered isn’t valid. You can style the field for when an value is entered using the :valid, :invalid or :required pseudo class (assuming you have the required attribute on the input) just like Locum Dr. Peter explained.

For more on styling forms using pseudo-classes the “CSS Ninja”, Ryan Seddon, has put together a great demonstration on A List Apart.

The specification details that one or more e-mail addresses are allowed. This means that the multiple attribute could be used with type='email' too.

Pretty cool, huh? Again, this highlights how HTML5 forms help to cut down the amount of JavaScript that you have to write when carrying out form validation.

There’s always a catch, though, right? At the time of writing, there is an internationalization issue with type='email'. When using it with double-byte internationalized domain names, the browsers invalidate them; so this example

isn’t valid in Firefox, Safari, or Chrome (there is no issue in Opera). However, a workaround has been created by Kyle Barrow that uses type='text' with the pattern attribute, as shown here:

An alternative solution is to continue using type='email' with the formnovalidate attribute on the submit button, as follows. This ensures that no validation will be carried out on form submission, which may or may not be suitable for your needs.

Internationalization issues aside, remember how we said there are dual benefits to HTML5’s input types—less development time and better user experience? Let’s go back and look at the iPhone once more, as shown in Figure 4.

Did you notice it this time? No? Look at the keyboard again. That’s right, the keyboard is different. There are dedicated keys for the @ and . characters to help you complete the field more efficiently. As we discussed with type='search', there is no downside to using type='email' right now. If a browser doesn’t support it, it will degrade to type='text'. And in some browsers, users will get a helping hand.

url

There is currently some debate about whether the user has to enter http:// into a field using input='url'. Browser vendors are discussing the possibility of pre-pending http:// to a URL following a check upon form submission. For up-to-date information, refer to the HTML5 specification.

The url input type, as you might expect, is for web addresses. You can use the multiple attribute to enter more than one URL. Like type='email', a browser will carry out simple validation on these fields and present an error message on form submission. This is likely to include looking for forward slashes, periods, and spaces, and possibly detecting a valid top-level domain (such as .com or .co.uk). Use the url input type like so:

Again, we’ll take a look at how the iPhone renders type='url'. As you can see in Figure 5, it has again updated the onscreen keyboard to ensure that completing the field is as simple as possible for the user by swapping the default space key for period, forward slash, and .com keys. (To access more endings like .org and .net, tap and hold the .com key.)

tel

tel differs from email and url in that no particular syntax is enforced. Phone numbers differ around the world, making it difficult to guarantee any type of specific notation except for allowing only numbers and perhaps a + symbol to be entered. It’s possible that you can validate specific phone numbers (if you can guarantee the format) using client-side validation. type='tel' is marked up as follows:

Once more, the iPhone recognises type='tel', only this time it goes one step further and completely changes the keyboard to the standard phone keyboard, as shown on the left in Figure 6. In addition to the iPhone, some Android devices (such as HTC Desire, shown on the right in Figure 6) also display a numeric keyboard for type='tel'. That’s pretty handy, don’t you think? Nice, big keys for entering a phone number help you to get that big, nasty form completed quickly.

number

number, as you might expect, is used for specifying a numerical value. As with the majority of these new input types, Opera was the first to implement type='number'. It, Safari, and Chrome render the input as a spinbox control (see Figure 7) whereby you can click the arrows to move up or down. Or if you prefer, you can type directly into the field. Firefox, on the other hand, renders the field like a standard text box. Support for type=”number” is in IE 10 also, although if you enter a non-numerical character the field empties when focus is lost and no feedback is provided to the user.

With the additional attributes min, max, and step we can change the default step value of this spinbox control as well as set minimum, maximum, and starting values (using the standard HTML value attribute). This example shows how these attributes work:

In this example, min represents the minimum value the field will accept, and max represents the maximum value. If we reach the maximum or minimum value, the appropriate arrow on the spinbox control will be greyed out so you can no longer interact with it. step is the increment that the value should adjust up or down, with the default step value being 1. This means we can include negative values or step up in increments of 0.5 or 5. value is that attribute you’re used to from previous versions of HTML. Each of the attributes are optional, with defaults being set if they aren’t used.

In contrast to Opera’s implementation, the iPhone (Figure 8) and some Android devices (such as HTC Desire, shown on the right in Figure 6-13) simply render the field as a standard text box but optimize the keyboard for easy input.

To make the iPhone render with the standard telephone keypad as we saw for type='text' Chris Coyier, of CSS Tricks devised a little hoax you can use. Rather than using type=”number”, use a standard type='text' input and add a pattern attribute that accepts only numbers, as shown below. This solution isn’t ideal but if you think it could be useful, Chris has put a short video together showing it in action.

Chris’ technique may soon become absolete though with the introduction of the inputmode attribute. The attribute, recently added to the specification will allow users to specify the type of input mechanism that is most useful for users. When implemented, you will be able to choose between numeric, latin, email, or kana input modes.

range

Note: For browsers that don’t support type='range', Remy Sharp has created a JavaScript polyfill to plug the gaps. You can find out more about it on his blog.

The range input type is similar to number but more specific. It represents a numerical value within a given range. Why the difference, I hear you cry? Because when you’re using range, the exact value isn’t important. It also allows browsers to offer a simpler control than for number. In Opera, Safari, Internet Explorer 10 and Chrome, type='range' renders as a slider (see Figure 6-14). When moving the slider in IE 10 a tooltip appears showing the current value. Additionally, in Opera, if the CSS defines the height greater than the width, the slider control will be rendered vertically as opposed to the standard horizontal rendering.

The following code shows how we might mark up our skill level on a scale of 1 to 100 by setting the min and max attributes (see Figure 9). We can also set the starting point for range using the value attribute.

Dates and times

You may have noticed that there isn’t a type='year' input type defined in HTML5. The reason for this is a lack of relevant use cases. All the use cases for a year input type that have been proposed can be achieved using type='number'.

If you’ve ever booked tickets online, you will have come across date pickers to help you quickly and easily choose the date you require. Perhaps you’ve even implemented a date picker on your own website. Generally, this is done using a JavaScript library such as jQuery, Dojo, or YUI. It can be a pain when you need to load a whole library and associated plug-ins just to implement a simple date picker. Well, with HTML5 we get that functionality baked into the browser. Not only that, but we don’t have to stop at just electing a single date; we can select a week, month, time, date and time, and even date and time with a time zone using the different input types. The markup is pretty straightforward.

You can go a step further by using the min and max attributes to ensure the user can only choose from a specified date range.

As with many of the other form implementations, Opera leads the way (support in other browsers is varied). Let’s take a look next at how browsers render these input types.

Input Min Max

date

Figure 10 shows Opera 10.5’s rendering of type='date'.

These date pickers aren’t restricted to desktop devices; some Blackberry devices and Chrome for Android render its internal date picker when used with type='date' (see Figure 11).

month

Next up, Figure 12 shows type='month', which might, for example, be used for a credit card expiry date.

week

You can also drill down to type='week'. Notice how Opera highlights a specific week using the same date picker control, as shown in Figure 13.

time

You can see in Figure 14 that type='time' renders a spinbox similar to that used earlier for selecting the precise time.

datetime

We can combine the date and time by using type='datetime' for specifying a precise time on a given day, as shown in Figure 15.

datetime-local

Finally, Figure 16 shows that we can achieve slightly more granular control by selecting a precise time on a given day with a local time zone variation using type='datetime-local'.

Date and time caveats

There are two caveats with these implementations. First, with the current implementation, it isn’t possible to type a date into the field (in all browsers). The date picker is keyboard accessible, though. However, we can foresee a potential issue; if implemented on a form that a data entry clerk regularly completes, they are likely to be quicker at typing the date than tabbing through with the keyboard or selecting from a date picker. Second, it isn’t possible to style the look of the date picker. We tend to think that this is a good thing, as users will receive a common experience across all websites they visit (provided they use the same browser all the time). Undoubtedly, though, corporations will require a branded date picker. Safari 5 and Chrome 5 have implemented these input types, but, unfortunately, they aren’t very user friendly. Dates have to be entered in the same format as the time element that we met earlier in the book. So for dates, the format would be YYYY-MM-DD, and for dates with time, a user would have to enter YYYYMM-DDT00:00Z, which is not very friendly at all.

As with the other new input types, if a browser doesn’t recognize them, it will simply default back to type='text' and let the user continue to use your JavaScript date picker.

color

The color input type is pretty self-explanatory: it allows the user to select a color and returns the hex value for that color. It is anticipated that users will either be able to type the value or select from a color picker, which will either be native to the operating system or a browser’s own implementation. Opera 11 has implemented type=”color” with a simple color picker that offers a number of standard color choices or the option to select Other, which brings up the operating system color picker (shown on the right in Figure 17).

In contrast, certain Blackberry devices have implemented the color input type that renders a color picker, as shown in Figure 18.

Input types summary

By using HTML5’s new form input types right now, we can enhance the user’s experience, future-proof our site, and make our life as developers easier. Obviously, we can’t just leave the browsers that don’t support all these new features hanging, and in Chapter 6 of Beginning HTML5 and CSS3 we take a look at how to detect support for these form features using JavaScript.

You can find a dummy form, using some of the examples we’ve shown in this article at our HTML5 forms demo page.

Input

We’ve hinted throughout the article at which browsers have support for HTML5 forms input types and attributes. With new versions of browsers being released at an ever-increasing rate, it can be difficult to keep up with what is or isn’t supported. If you want to keep an eye on the current progress, we suggest visiting When can I use … or FindMeByIP or Wufoo’s HTML5 forms research.

If you missed the first article in this series on HTML5 forms, why not read a brief History of HTML5 forms and learn all about the new attributes introduced.

This is article is an excerpt from Chapter 6 of Beginning HTML5 and CSS3: The Web Evolved by Christopher Murphy, Oli Studholme, Richard Clark and Divya Manian, published by Apress.

Find the minimum and maximum value in an array

Difficulty: Medium
Asked in: Facebook

Understanding the Problem

Problem Description: Given an array A[] of size n, you need to find the maximum and minimum element present in the array. Your algorithm should make the minimum number of comparisons.

For Example:

Input: A[] = { 4, 2, 0, 8, 20, 9, 2}

Output: Maximum: 20, Minimum: 0

Input: A[] = {-8, -3, -10, -32, -1}

Output: Maximum: -1, Minimum: -32

Possible follow-up questions to ask the interviewer :-

Input Type Number Min

  1. Are the array elements necessarily positive? (Ans: No, they can be positive, negative, or zero)
  2. Are the array element sorted ? (Ans: No, they can be in any order)
  3. Can the array contain duplicates? (Ans: Sure, that's a possibility.)

Problem Note:- The interviewer would not judge your algorithm for this question based on the time complexity as all solution has the time complexity of O(n). The bottleneck parameter in this problem is the number of comparisons that your algorithm requires to determine the maximum and the minimum element. You need to decrease the number of comparisons as much as you can.

Solutions

  1. Searching linearly: Increment the loop by 1
  2. Divide and Conquer: Tournament Method
  3. Comparison in pairs: Increment the loop by 2

1. Searching linearly: Increment the loop by 1

We initialize both minimum and maximum element to the first element and then traverse the array, comparing each element and update minimum and maximum whenever necessary.

Pseudo-Code
Complexity Analysis

At every step of the loop, we are doing 2 comparisons in the worst case. Total no. of comparisons (in worst case) = 2*(n-1) = 2n - 2

Time complexity = O(n), Space complexity = O(1)

In the best case, a total of n-1 comparisons have been made. (How?)

Critical ideas to think!
  • We have initialized maximum and minimum with the first element of the array - why?
  • What would be the best case and worst case input?
  • How can we decrease the number of comparisons made here?

2. Divide and Conquer : Tournament Method

Another way to do this could be by following the divide and conquer strategy. Just like the merge sort, we could divide the array into two equal parts and recursively find the maximum and minimum of those parts. After this, compare the maximum and minimum of those parts to get the maximum and minimum of the whole array.

Solution Steps
  1. Write a recursive function accepting the array and its start and end index as parameters
  2. The base cases will be
  • If array size is 1, return the element as both max and min
  • If array size is 2, compare the two elements and return maximum and minimum
Input Min Max

3. The recursive part is

  • Recursively calculate and store the maximum and minimum for left and right parts
  • Determine the maximum and minimum among these by 2 comparisons

4. Return max and min.

Pseudo Code
Complexity Analysis

Input Min Max

For counting the number of comparisons, since this is a recursive function, let us define the recurrence relation :

Time complexity = O(n) and space complexity = O(logn) (For recursion call stack)

Input Min Max Value Html

If n is a power of 2, the algorithm needs exactly 3n/2–2 comparisons to find min and max. If it's not a power of 2, it will take a few more(not significant).

Html number input min max
Critical ideas to think!
  • How do we analyze the recursion by the master's theorem and recursion tree method?
  • How is the space complexity derived to be O(logn)?
  • Why there are 2 base cases? What if we remove the base case with array size 2?
  • Why prefer mid = start + (end - start)/2 over (start + end)/2 when calculating middle of the array ?
  • Can the number of comparisons be decreased further?

3. Comparison in Pairs : Increment the loop by 2

In this approach, we pick array elements in pairs and update the min and max. If the array size is odd, we initialize the first element as both min and max, and if it's even, we compare the first two elements and initialize min and max accordingly.

Solution Steps
  1. Create max and min variables.
  2. Check for the size of the array
  • If odd, initialize min and max to the first element
  • If even, compare the elements and set min to the smaller value and max to the bigger value

3. Traverse the array in pairs

4. For each pair, compare the two elements and then

  • Compare the bigger element with max, update max if required.
  • Compare the smaller element with min, update min if required.

5. Return max and min.

Pseudo Code
Complexity Analysis

Time Complexity is O(n) and Space Complexity is O(1).

For each pair, there are a total of three comparisons, first among the elements of the pair and the other two with min and max.

Total number of comparisons:-

  • If n is odd, 3 * (n-1) / 2
  • If n is even, 1 + 3*(n-2)/2 = 3n/2-2
Critical ideas to think!
  • Why min and max are initialized differently for even and odd sized arrays?
  • Why incrementing the loop by 2 help to reduce the total number of comparsion ?
  • Is there any other way to solve this problem? Think.
  • In which case, the number of comparisons by method 2 and 3 is equal?

Comparison of different solutions

Suggested Problems to solve

  • Find the smallest and second smallest element in the array using minimum number of comparsions
  • Find the minimum element in a sorted and rotated array
  • Find Kth largest element in an array
  • Find K largest element in an array
  • Find the middle element among three numbers
  • Find median of k sorted arrays

Please write comments if you find any error or bug. Happy Coding! Enjoy Algorithms!

AfterAcademy Data Structure And Algorithms Online Course - Admissions Open