Reputation: 1194
I have been searching SO for a good answer for this specific question, however many of the answers are from 2012 or earlier and advances in CSS may already tackle this.
If I have an input box which is only one character wide (lets assume 8px) is there a way to have this box expand on user input to grow with the size of the input? I have tried using contenteditable="true"
but this did not seem to take any effect with an input box. Multiple attempts at adjusting the width did not take any effect.
Working out of this JSFiddle
NOT A CSS SOLUTION
But this is what I ended up doing with jquery
$("input").bind('keyup', function(){
var inputLength = $(this).val().length
if(inputLength > 0){
$(this).attr("size", $(this).val().length)
}
else{
$(this).attr("size", "1")
}
});
Upvotes: 1
Views: 1080
Reputation: 9634
You can use some html element with contenteditable
attribute, than grab its content on input
event, check it out:
$('[data-store]').each(function(i) {
var thisContent = $(this);
var remoteInput = $( thisContent.data('store') );
thisContent.on('input', function(e) {
remoteInput.val( $(this).text() );
$('#current_value').text( remoteInput.val() );
});
});
[contenteditable] {
padding: 0 5px;
border: 1px solid #c0c0c0;
display: inline-block;
vertical-align: middle;
min-width: 5%;
white-space: nowrap;
height: 30px;
line-height: 30px;
overflow: hidden;
}
[contenteditable]:focus,
[contenteditable]:hover {
border: 1px solid #000;
}
[contenteditable] br {
display: none;
}
[contenteditable] * {
display: inline;
white-space: nowrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p><span maxlength="10" value="1" contenteditable="true" data-store="#yourtext"></span></p>
<input type="hidden" id="yourtext" name="yourtext" />
<p>The hidden input value: <b><span id="current_value"></span></b></p>
Upvotes: 1
Reputation: 1277
I am not sure if the contenteditable attribute works on input fields. Any other element with this attribute works fine.
In my fiddle, I have made a div with content editable set to true. You can change the styles to make it look like an input box. And support both min-width of the input field and max-width
HTML
<div contenteditable="true"></div>
CSS
div {
min-width: 8px;
display: inline-block;
border: 1px solid #DADADA;
padding: 2px 5px;
max-width: 200px;
}
http://jsfiddle.net/3079afmk/2/
Upvotes: 0
Reputation: 357
Changing your .inputbox css a bit to this:
.inputbox {
border: solid 1px black;
background-color: green;
display:inline-block;
margin: 20px;
}
As long as there are no spaces it should expand, you gave it a max-width which was part of the problem, telling it not to grow past a certain point. The display: inline-block so of expands/contracts based on the widest content.
Upvotes: 0