Canon 5d руководство по ремонту audi а6 руководство по эксплуатации асу 109 2009 Nissan руководство по ремонту honda civic руководство по ремонту умз руководство по качеству ооо Korg Pa 500 руководство по e36 bmw руководство по эксплуатации ups nokia x6 руководство пользователя руководство по вязанию современные интерпретации стилей руководства Dsc W120 Sony руководство по обращению с мужчинами театр под руководством джигарханяна Xerox 3140 руководство мтз руководство по эксплуатации авео tusl2 c руководство руководство по эксплуатации спринтер руководство по ремонту шевролет лачетти Sony Ericsson K790 руководство по ремонту volvo volkswagen golf руководство Mail Ru 142 pocketbook 301 руководство пользователя мультимедийное руководство по ремонту уаз Sanyo Bosch Sgs 46e52 Eu Kenwood Tk 150s руководство по эксплуатации toyota succeed руководство по эксплуатации panasonic 9 word 2007 руководство руководство по оральному Htc 5388 I samsung ml 1660 руководство руководство по сборке мебели 104 руководство по ремонту ваз 21074i а6 руководство скачать Beko Dfs 1500 руководство по эксплуатации мазда mpv acronis disk director руководство методическое руководство в доу руководство по ремонту газ 52 чем отличается лидерство от руководства 126 руководство по эксплуатации hyundai руководство по эксплуатации fiat doblo Ariston Arsl 105 1100 d link руководство выплаты за классное руководство Canon Digital Ixus 70 руководство по настройке руководство по ремонту foton Line 6 Spider руководство пользователя samsung b7722 руководство цб рф 318 Asus M4a89gtd Pro теория стилей руководства лайкерта 812 руководство хонда аккорд платц тойота руководство windows mobile 6.5 руководство пользователя руководство по эксплуатации визир Photo Dvd Maker Professional руководство по эксплуатации daf руководство администратора linux pdf Samsung мазда руководство по ремонту основные функции руководства руководство по ремонту двс matiz руководство по ремонту руководство по эксплуатации 2108 Sony Mex Dv160ue руководство по ремонту калдина 21099 скачать руководство Canon 400 asus n53j руководство пользователя руководство по 406 двигателю Lightroom 3 honda руководство по ремонту скачать Candy Holiday 104 D руководство по ремонту pajero руководство по ремонту mazda 3 Canon Lbp 5050 руководство по выживанию на пустошах Z610i полное руководство по самоубийству Canon 550d ipod touch 4g руководство пользователя руководство по эксплуатации снегохода руководство по ремонту автомобиля мерседес киа спектра руководство руководство к духовной жизни руководство windows vista скачать руководство по ремонту ровер 400 руководство по ремонту мтз скачать руководство по эксплуатации ниссан алмера руководство по ремонту ланцер диктаторский стиль руководства skype руководство пользователя 6500 руководство по обеспечению качества hover руководство по ремонту samsung gt s5230w руководство access 2003 практическое руководство руководство по ремонту рено эспейс руководство по ремонту мтз 82.1 руководство по ремонту ваз 21120 Canon G10 Indesit Kgb Vs 400 руководство по эксплуатации tomahawk 9030 hyundai accent руководство по эксплуатации руководство уфмс россии Sony Dsc S730 руководство пользователя edius руководство по эксплуатации шевроле круз руководство по эксплуатации вагонов Apc Smart Ups 1000 руководство по эксплуатации passat Htc Hero Android скачать руководство по ремонту canon руководство по расширенным операциям daewoo nexia руководство по эксплуатации ивеко дейли руководство по эксплуатации Janome L394 adobe premiere pro 2.0 руководство скачать клиническая фармакология национальное руководство Alligator 550 руководство по эксплуатации фольцваген пассат Bosch Silver S4 Samsung 5230 руководство по ремонту mitsubishi canter руководство по эксплуатации ваз 21144 создание руководства Panasonic Kx Tcd450 руководство по эксплуатации хонда интегра классификация и характеристика стилей руководства peugeot 207 руководство по эксплуатации Samsung 606 металлоконструкции 3d руководство пользователя руководство по ремонту ваз 2170 что называется стилем руководства руководство по эксплуатации шевроле тахо руководство по эксплуатации canon Panasonic nissan maxima a33 руководство руководство фольксваген пассат руководство по эксплуатации volkswagen caddy trailblazer руководство по ремонту cr v руководство по ремонту методы руководства менеджмент стили лидерства и руководства руководство nokia e51 руководство по эксплуатации bmw 5 идеальный стиль руководства
Creating a DHTML Spinbox
March 20th 2006 @ 11:02 pm Javascript, DHTML

Recently I was asked by a client if it would be possible to use a spinbox for a certain value in a web application I was building. Being totally sure this was going to be a piece of cake I said yes (it’s just a textbox with two arrows, right?). As it turns out, it is possible, only a little bit more complicated than I first thought.

The Spinbox

The spinbox is also called spinbutton, spincontrol or UpDown button. You can see it in the picture on the right. It is commonly used to enter, for example, time and dates in desktop applications but isn’t available as an HTML form element.

Placing the arrows

The greatest challenge by far was positioning the arrow images. I started trying to do it using css, but soon gave up when I encountered too many browser inconsistensies, bugs and missing features (such as missing inline-block in Firefox), and decided to do it the old-fashioned way instead: using tables. In my solution, a table is created dynamically around the textbox and made inline so that more than one spinbox can be laid out on the same line. Only problem is, Firefox and IE both don’t understand display:inline-table, they want display:inline instead, which Safari & Opera don’t like. The solution to that:

table.style.display='inline';
try {
    table.style.display = 'inline-table';
} catch(e) {}

Firefox just silently drops the inline-table declaration that it doesn’t understand but IE throws and error. That’s why the try/catch statement is needed.

PeriodicalExecuter

When one of the arrows is clicked, the value in the textbox should increase or decrease while the mouse button is held down. To accomplish this I created a Prototype PeriodicalExecuter which updates the textbox with increasing frequency. Only problem is, for some reason they’ve decided to not include a stop method for the PeriodicalExecuter. Luckily, someone else also ran into this problem. I’ve included that solution in my source.

Disable context menu

In Firefox on Mac, the context menu pops up when you hold down the left mouse button for a second or so anywhere in the window. This is obviously a bit annoying when you are trying to use the spinbox. Turns out that you can stop it from happening by denying the onContextMenu action from firing. In Prototype code:

Event.observe(img,'contextmenu',function(evt){Event.stop(evt);});

In HTML this would be:

<img src="pic.gif" oncontextmenu="return false;">

Files

Download the files here: tesSpinbox. You can try a live demo here: Demo.

Usage

Include prototype first, and then spinbox.js. Change the path to the images in spinbox.js (sb_imgpath) to point to where you uploaded the images. Then to convert any textbox into a spinbox:

new SpinBox(id_of_textbox,min_value,max_value,padded_length);

Padded_length is the desired length of the string in the textbox. If the string is shorter than this value, it will be padded with zeros. A padded_length of 3 would mean that 7 becomes 007, for example. A spinbox example:

<input type="text" id="myspin" size="2">
<script language="javascript">
    new SpinBox('myspin',0,59);
</script>

Will turn the textbox into a spinbox with a minimum value of 0, maximum value of 59 which is not zero-padded at all.

-Tomas Larsson
rss 15 comments
  1. Erik Lindegren
    March 22nd, 2006 | 9:31 am

    Wouldn’t it be nice to be able to add some kind of dependencies between different spinboxes. So when one spinbox reach a certain value it will increase/decrease another spinbox with a specified amount.

    E.g. in your demo, it would be nice if the hour spinbox increased with one when you’ve reached the max value of the minute spinbox, and that the minute spinbox restarted counting from one.

    Great work by the way!

  2. March 23rd, 2006 | 2:24 pm

    Thanks for the suggestion Erik! That will definitely be in the next version of the spinbox!

  3. Eric Binger
    March 23rd, 2006 | 6:03 pm

    Hi !

    i’ve installed it on a web page and see the spinboxes for an hour introduction. The web page is fine.

    But there’s a glitch :/ the variables don’t POST in the HTTP_POST_VARS. My program can’t get these value.

    I use POST type form.

    Any idea ?

  4. Mike Greubel
    March 23rd, 2006 | 8:08 pm

    Very good work. I’m just learning Javascript and try many things such as Ajax. So I found prototype and your blog to stop a PeriodicalExecuter. So I tried your Spinbox.

    My Question is now: Is it possible to create the javascript spinbox object with no html dom eventhandler? I have scripts, which load div.innerHTML and in this code is the defined. But it doesn’t exist at load-time. What can I do then?

  5. March 23rd, 2006 | 8:40 pm

    Eric Binger: Did you copy the text inputs directly from the demo.html file? In that case you need to add name attributes to them before they work, i.e. <input type=”text” name=”name_of_input”>. If that’s not the case, what browser are you using?

    Mike Greubel: You can create the spinbox anytime! It doesn’t need to be done at load-time. You can also provide the constructor with the actual textbox object rather than the id of the textbox. In your case however, you could just initialize the spinbox normally after the textbox has been created inside the div (if I’m understanding you correctly).

  6. Eric Binger
    March 24th, 2006 | 8:41 am

    Hi Tomas !

    yes i create the

    new SpinBox(’minutespassage’,0,59,2);

    I use mozilla on Linux ; have also tried Firefox, same issue :/

    Good work anyway :)

  7. Eric Binger
    March 24th, 2006 | 9:05 am

    Hi again !

    my previous message has been truncated !

    i have take a look on your javascript source ; i think there is perhaps a mixup with ‘disabled’ attribute.

    Of course when a field is disabled the browser doesn’t send it to server ; the attribute ‘readonly’ make the field locked AND sended to server…

    cya !

  8. Ramesh
    April 5th, 2006 | 8:15 am

    Hi,

    I liked your spin button; I was trying to dynamically create the objects using PHP
    and getting flowing error:
    Error1:
    Line:34
    Char:1
    Error’PeriodicalExecuter’ is undefined
    Code:0
    URL: file://C:\Documents and Settings\rramani.AGILE\Desktop\Untitled.htm
    Error2:
    Line: 159
    Char: 5
    Error:’toolbar[…].0′ is null or not an object
    Code: 0

    Any clue on why I am getting this error

  9. April 14th, 2006 | 11:26 am

    Ramesh:
    Have you included the prototype javascript library? Sounds like it can’t find the PeriodicalExecuter which is part of the prototype library

  10. August 18th, 2006 | 2:20 pm

    Good Work!
    Clean and easy code and greate component!

    I finded a little bug and posted at sourceforge and create a feature request too asking for set the step size.

    []’s
    Vinícius Pitta Lima de Araújo

  11. December 10th, 2006 | 10:35 pm

    Nice use of the periodical executor. I’ll have to think of a need to use the spinbox :)

  12. Gun
    January 23rd, 2007 | 11:18 am

    Thx. Great work. And saved me a lot of work.

  13. Dupe
    July 12th, 2007 | 9:13 am

    Hi Tomas,

    Thanks for your spinbox. I modified it to display time in just one spinbox. So instead of
    separate spinboxes for hour, minutes, and seconds. A single spinbox shows all the
    information (hh:mm:ss). By incrementing the seconds up to the maximum limit,
    increments the minutes part. Also, incrementing the minutes part up to the
    maximum limit increments the hour part.

  14. Samriti
    July 30th, 2007 | 5:52 am

    I don’t know how to create spinbox in javascirpt and dhtml plzzz tell me

  15. Narendra
    November 17th, 2007 | 5:10 am

    Hi Thomas,
    I searched lot of websites in google, but I didn’t find how to create spin box and spin buttons. Finally, I got your link and I downloaded your files which you have kept in website. It’s work fine. good work by you. Thank you.

comment on this article

Notice: All comments are moderated. Your comment will appear once approved.