Tuesday, September 25, 2012

How to make a select editable using jQuery

I'm sure some of you had or have the need to make a html drop-down list editable. Well, if you didn't I did.

There are a lot of neat plug-ins out there, but, if you found yourself in a situation like me (compatibility issues), you'll definitely want/try to do it by yourself. Let me save you some time. I'll just copy/paste my code, works great under FF, Chrome, Opera, IE.

HTML:


Enter custom value in a select element
The trick is to hide the text field (using a CSS), and, when 'custom' is selected, show it. There's a onKeyUp event, when triggered, changes the value of the 'custom' child of the select.

<select id="select_element" name="select_element">
 <option value="1">1</option>
 <option selected="selected" value="2">2</option>
 <option value="3">3</option>
 <option value="4">4</option>
 <option id="custom_value" value="">custom</option>
</select>
<input id="custom" name="custom" type="text" />

jQuery code:

$(document).ready(function(){
//  enter a custom value 
$('#select_element').change(function(){
 if($(this).prop("selectedIndex") == 4){
 $('#custom').css('position','absolute');
 $('#custom').css('left',$(this).css('left'));
// add a pixel or two to the top, FF doesn't align the objects right 
 $('#custom').css('top',$(this).css('top')+2);
 $('#custom').css('width','40px');
// same as the top property
 $('#custom').css('height',$(this).css('height')-1);
 $('#custom').show();
 $('#custom').focus();
}
else{
 $('#custom').hide();
}
});
//  if the value changes, change the dropdown value also
$('#custom').keyup(function(){
 $('#custom_value').val($(this).val());
 console.log('The value you typed is:'+$('#custom_value').val());
});
});

and , finally , CSS:

body{
position: absolute;
width: 100%;
height: 100%;
margin:0px;
padding: 0px;
font-family: Arial, sans-serif;
}
#header_para{margin-left: 20%;}
.contentWrapper{margin-left:180px;}
#custom{
display:none;
z-index: 100;
position: relative;
float: left;
width: 43px;
margin: 0px;
}
#select_element{
z-index: 0;
position: absolute;
width: 60px;
}

and link to all of this:

edit_select.zip

I hope you'll find this usefull.

No comments:

Post a Comment