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