jQuery HTML select element with editable input field

A few days ago I had a small task which invloved building a simple non-scientific calculator, some fields with changeable values. The thing was it had some select tags that the user could edit the value. I’m sure there are plugins out there to do this job but I didnt wanted extra unnecessary code , just something something quick and simple. Here is how I did it, maybe it will help you.

html file

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>tutorial</title>
        <link rel="stylesheet" href="reset.css">
        <link rel="stylesheet" href="style.css">
        <script src="jquery-1.8.3.min.js"></script>
    </head>
    <body>
        <select>
           <option selected="selected" value="100">100</option>
           <option value="200">200</option>
           <option value="300">300</option>
           <option value="400">400</option>
        </select>
        <input type="text" name="" value="">
        <p>value:</p>
        <script src="jquery.calculator.js"></script>
    </body>
</html>

style.css

select{position:absolute; width:160px; height:23px; left:0; top:0; border:0;}
input{position: absolute; width: 140px;height:17px; left:0; top:0;}
p{position: relative; margin-top:50px;}

jquery.calculator.js

var $input = $('input');
var $select = $('select');

$select.change(function(){
 modify();
})

function modify(){
 $input.val($select.val());
 output();
}

function output(){
 $('p').text('value: ' + $input.val());
}

$input.on('click', function(){
 $(this).select()
}).on('blur', function(){
 output();
})

modify();

This is what you should get: jsfiddle

Try selecting a number from the list or click on the text box to add your own number.
Ofcourse this could be done more elegant but I wanted to show an idea of how could be done.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s