Dynamically Adjust HTML Text Input Width to Content - javascript

I can't quite find a clear answer on this, and excuse me if there is one I've missed.
I want my text input widths to automatically adjust to the size of the content within them. First with placeholder text than the actual text someone inputs.
I've created the below as an example. Currently, the boxes are far bigger than my placeholder text, causing huge amounts of white space, and it's obviously the same thing when I type in something.
I've tried width auto, some jQuery, and twine and bubble gum I found on the internet. But nothing has worked yet. Any thoughts? Thanks!
HTML:
<span><p>Hello, my name is </p></span>
<span><input type="text" id="input" class="form" placeholder="name"></span>
<span><p>. I am </p></span>
<span><input type="text" id="input" class="form" placeholder="age"></span>
<span><p> years old.</p></span>
CSS:
.form {
border: 0;
text-align: center;
outline: none;
}
span {
display: inline-block;
}
p {
font-family: arial;
}
Fiddle

One possible way:
[contenteditable=true]:empty:before {
content: attr(placeholder);
color:gray;
}
/* found this online --- it prevents the user from being able to make a (visible) newline */
[contenteditable=true] br{
display:none;
}
<p>Hello, my name is <span id="name" contenteditable="true" placeholder="name"></span>. I am <span id="age" contenteditable="true" placeholder="age"></span> years old.</p>
Source for CSS: http://codepen.io/flesler/pen/AEIFc.
You'll have to do some trickery to pick up the values if you need the values for a form.

Use onkeypress even
see this example :http://jsfiddle.net/kevalbhatt18/yug04jau/7/
<input id="txt" placeholder="name" class="form" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';"></span>
And for placeholder on load use jquery and apply placeholder
size in to input
$('input').css('width',((input.getAttribute('placeholder').length + 1) * 8) + 'px');
Even you can use id instead of input this is just an example so that I
used $(input)
And in css provide min-width
.form {
border: 1px solid black;
text-align: center;
outline: none;
min-width:4px;
}
EDIT:
If you remove all text from input box then it will take placeholder value using focusout
Example: http://jsfiddle.net/kevalbhatt18/yug04jau/8/
$("input").focusout(function(){
if(this.value.length>0){
this.style.width = ((this.value.length + 1) * 8) + 'px';
}else{
this.style.width = ((this.getAttribute('placeholder').length + 1) * 8) + 'px';
}
});

input.addEventListener('input', event => event.target.style.width = event.target.scrollWidth + 'px');
Unfortunately this will only increase the size of the input. If you delete characters the size will not decrease. For some use cases this is perfectly fine.

Kevin F is right, there is no native way to do it.
Here is a one way to do it if you really want it to happen.
In the code, there is an invisible span where the text is placed. Then we retrieve the width of the span.
https://jsfiddle.net/r02ma1n0/1/
var testdiv = $("#testdiv");
$("input").keydown( function(){
var ME = $(this);
//Manual Way
//var px = 6.5;
//var txtlength = ME.val().length;
//$(this).css({width: txtlength * px });
testdiv.html( ME.val() + "--");
var txtlength = testdiv.width();
ME.css({width: txtlength });
});

Try with 'size' attribute.
This will work even when you clear the text .
Need jQuery to work this
<div>
<input id="txt" type="text" style="max-width: 100%;" placeholder="name">
</div>
<script>
$(document).ready(function() {
var placeholderLen = $('#txt').attr('placeholder').length;
// keep some default lenght
placeholderLen = Math.max(5, placeholderLen);
$('#txt').attr('size', placeholderLen);
$('#txt').keydown(function() {
var size = $(this).val().length;
$(this).attr('size', Math.max(placeholderLen, size));
});
});
</script>

Related

How to get Formee legend border to grow with DOM elements added programmatically

So I have an application where a user should be able to add an indeterminate number of paired text boxes representing the name and phone number of a person to be submitted to a database. The relevant markup is below...
<div id="divAddVoters">
<form class="formee" action="">
<fieldset id="appendVoters">
<legend>Enter Voter Name and Phone Number:</legend>
<!--<div id="appendVoters">-->
<div class="grid-4-12" id="appendVoterName">
<label>Name:</label>
<input type="text" class="txtAddVoter" value="" />
</div>
<div class="grid-4-12" id="appendVoterNumber">
<label>Phone Number</label>
<input type="text" class="txtAddNumber" value="" />
</div>
<div class="grid-4-12"></div>
<!--</div>-->
<div class="grid-12-12">
<button id="btnAddVoter" class="formee-button"
onclick="addVoter(); return false;">ADD VOTER</button>
<button id="btnSubmitVoters" class="formee-button"
onclick="submitVoters(); return false;">SUBMIT VOTER(S)</button>
<p id="pError"></p>
</div>
</fieldset>
</form>
</div>
...so if the user selects the btnAddVoter button any number of times, any number of txtAddVoter text boxes should be added to div appendVoterName and txtAddNumber text boxes should be added to div appendVoterNumber. The javascript function to do this is below...
function addVoter()
{
$('fieldset#appendVoters div#appendVoterName').append("<label>Name</label><input type='text'" +
"class='txtAddVoter' value='' />");
$('fieldset#appendVoters div#appendVoterNumber').append("<label>Phone Number</label>" +
"<input type='text' class='txtAddNumber' value='' />");
}
I'm using Formee to make everything look nice, which explains the fieldset, legend and form class="formee" (my application is actually entirely javascript driven, so I don't need a form at all except that formee styles demand it). The problem is that the border drawn by the legend tag does not grow with the elements added inside of it, so as a user adds textboxes the eventually they overrun the bounds of the legend, over the buttons, and the whole thing looks completely ridiculous.
I'm wondering what the best way to make the legend border grow with the number of contained textbox elements would be. I was thinking about maintaining a count of textboxes, and when they reach a certain number using javascript/jQuery to alter the Formee style sheet to make the legend larger? Not quite sure how to go about this, though, looking for some good ideas.
EDIT - Ok, here's the relevant portion of CSS...
.formee fieldset {
border: 1px solid #d4d4d4;
position: relative;
height:30%;
padding: 1.2em 0;
margin: 0 0 4em;
}
What I want to do is, every time the user adds a textbox pair, read out the height attribute value, double that value, and then set this value as the new height in this CSS rule. Is this possible?
EDIT - I ended up making it happen with this function...
function doubleFieldSetSize(divName)
{
var height = $('fieldset#' + divName).css('height');
height = height.replace(/px$/, '');
height = parseInt(height) + 70;
height = height + "px";
$('fieldset#' + divName).css('height', height);
}
Try to add this css, float and height?
.formee fieldset {
float:left;
height:auto;
border: 1px solid #d4d4d4;
position: relative;
padding: 1.2em 0;
margin: 0 0 4em;
}

Alter input type="file" label content

I was wondering if there is any way to hide or change the content of the default label:No file chosen for
<input type="file" id="myFileInput"/>
What I come up with so far is to decrease its length by half, so that it displays a tooltip.
$('input:file').css('width', parseFloat($($('input:file')).css('width'))/2 );
Any Ideas?
You cannot change input file design as its native to each browser. But you still can simulate it, sorry hacky:
See DEMO
<button id="btn_myFileInput">Choose file...</button>
<label for="btn_myFileInput">No file choosen or whatever...</label>
<input type="file" id="myFileInput" multiple />​
JS:
$(function () {
$('#btn_myFileInput').data('default', $('label[for=btn_myFileInput]').text()).click(function () {
$('#myFileInput').click()
});
$('#myFileInput').on('change', function () {
var files = this.files;
if (!files.length) {
$('label[for=btn_myFileInput]').text($('#btn_myFileInput').data('default'));
return;
}
$('label[for=btn_myFileInput]').empty();
for (var i = 0, l = files.length; i < l; i++) {
$('label[for=btn_myFileInput]').append(files[i].name + '\n');
}
});
});
You can also proceed in this way, but it is an hack:
<input type="file" id="myFileInput" name="html" style="width: 90px;" onchange="this.style.width = '100%';"/>
Chrome was giving me this problem too. I tried to set all sorts of CSS selectors, but nothing seemed to work well. However, I did find a solution by using the FORM element.
name your input[type=file] element.
name your form element and put the input[type=file] in it.
make a span and place it below the input in the form. This will be your label.
use CSS to set the input's height to 0px and opacity to 0, this will make it invisible.
make the span positioned absolutely and to the left 0px.
<style>
#file {
height:0px;
opacity:0;
}
#span {
left:0px;
position:absolute;
cursor: pointer;
}
</style>
<form name="form">
<input type="file" id="file" name="file"/>
<span id="span">My File label!!!!</span>
</form>
<script>
var span = document.getElementById("span");
span.onclick = function(event) {
document.form.file.click(event);
};
var span = document.getElementById("span");
span.onclick = function(event) {
document.form.file.click(event);
};
</script>
I tested this in Chrome and FF, not ie, but I hope this helps.
jsfiddle http://jsfiddle.net/aressler38/L5r8L/1/
Simple style with just CSS. You HTML button will read attributes from CSS. No need javascript slowing down the page.
CSS should be as below:
.editable:empty:before {
content: attr(data-placeholder);
}
.custom-file-input::before {
content: attr(placeholder);
/* content: 'Select some files'; */
}
input button should be:
<input class="custom-file-input" placeholder="#Hashtags " bind:files id="many" multiple type="file" />

How do I display a Hint box or Tooltip while the user is typing?

I have about 1000 Textfields on our page, and need to display a Tooltip above the textfield that the user is currently typing in.
It sounds simple, but I'm having difficulty figuring out how to display it on top of everything else on the page and without breaking flow of the document.
I can't use any external libraries for this either, which makes it a little more difficult. I am only allowed to use pure JS (or a language that compiles to pure JS, such as TypeScript).
Does anyone have any links, tutorials or anything like that? It would be very helpful.
Thank you
Edit:
I am aware that you can use the Title attribute on an element, however this tooltip needs to have more than just text inside it and needs to be bigger and directly above the textbox.
Something like this might help you:
http://jsfiddle.net/ysuw5/
<div id="container">
<input type="text" class="tooltip" onfocus="theFocus(this);" onblur="theBlur(this);" title="asdf" /><br />
<input type="text" class="tooltip" onfocus="theFocus(this);" onblur="theBlur(this);" title="asdf2" /><br />
<input type="text" class="tooltip" onfocus="theFocus(this);" onblur="theBlur(this);" title="asdf3" /><br />
<input type="text" class="tooltip" onfocus="theFocus(this);" onblur="theBlur(this);" title="asdf4" /><br />
<div id="tooltip"></div>
</div>
function theFocus(obj) {
var tooltip = document.getElementById("tooltip");
tooltip.innerHTML = obj.title;
tooltip.style.display = "block";
tooltip.style.top = obj.offsetTop - tooltip.offsetHeight + "px";
tooltip.style.left = obj.offsetLeft + "px";
}
function theBlur(obj) {
var tooltip = document.getElementById("tooltip");
tooltip.style.display = "none";
tooltip.style.top = "-9999px";
tooltip.style.left = "-9999px";
}
This is clearly very narrow-minded and would need to be modified to fit exactly what you need. I didn't bother binding the focus and blur events with Javascript - it would be better than putting them in the HTML.
You can use “CSS tooltips” in many ways. A relatively simple idea is to place the hint content in a div, initially hidden with CSS, right before the field. Then you need an onfocus event handler that changes that div to visible (and an onblur handler that makes it invisible again). You would have a container for the hint and the field and declare that container as relatively position, to make it possible to position the hint “absolutely” (that is, relatively to the container).
Example (jsfiddle):
<!DOCTYPE HTML>
<meta charset=utf-8>
<style>
.textfield {
position: relative;
}
.textfield .hint {
display: none;
position: absolute;
width: 10em;
bottom: 1.3em;
background: #ff9;
padding: 0 0.2em;
border: solid 1px;
}
</style>
<script>
function hint(elem) {
elem.parentNode.firstElementChild.style.display = 'block';
}
function unhint(elem) {
elem.parentNode.firstElementChild.style.display = 'none';
}
</script>
<p>This is just some filler text.
<table>
<tr>
<td><label for=bar>Bar</label>
<td>
<div class=textfield>
<div class=hint>This is hint text for the Bar field.</div>
<input id=bar name=bar onfocus="hint(this)" onblur="unhint(this)">
</div>
<tr>
<td><label for=foo>Foo</label>
<td>
<div class=textfield>
<div class=hint>This is hint text for the Bar field.</div>
<input id=foo name=foo onfocus="hint(this)" onblur="unhint(this)">
</div>
</table>
(When using a table to structurize your form, in this approach you need to remember that a CSS positioning does not work for table cells. This is why you cannot use the td element as wrapper but need to use div inside it.)

Jquery Font Size Manipulation TextArea Cutout

I have a text area that I want to change the font size of the text using a + and a - button.
I know how to get the font size to change using javascript/jquery. That all works great. However my problem is that as the font size grows it begins to stretch out of the text box. The top half of the first row will be tucked under the top bar of the text input area. I tried adjusting the line height proportionally to the increase in font size but it doesn't seem to solve the problem
here is my code:
HTML
<div style="color: #0D1E28">
-
<a href ="#" id="resetfont">
<span style="font-size: 9px; letter-spacing: -3px;">A</span>
<span style="font-size: 16px;">A</span>
</a>
+
</div>
<textarea name="txtOutput" id="txtOutput" style="width: 600px; height: 550px; line-height: 8.5; overflow: auto; font-size: 21.5px;" rows="2" cols="20" readOnly="readonly">
</textarea>
JavaScript
$(document).ready(function () {
$("#plustext").click( function () { resizeText(1); });
$("#minustext").click( function () { resizeText(-1); });
$("#resetfont").click(function () { $("#txtOutput").css('font-size', "14px"); });
});
function resizeText(multiplier) {
if ($("#txtOutput").css('font-size') == "") {
$("#txtOutput").css('font-size', "12px");
var currentFontSize = $("#txtOutput").css('font-size');
var currentFontSizeNum = parseFloat(currentFontSize, 10);
var newFontSize = (currentFontSizeNum + (multiplier * 0.5)) + "px"; ;
var currentLineHeight = $("#txtOutput").css('line-height');
if (currentLineHeight == "normal") {
currentLineHeight = "1";
}
var currentLineHeightNum = parseFloat(currentLineHeight, 10);
var newLineHeight = (currentLineHeightNum + (multiplier * 0.5));
$("#txtOutput").css('line-height', newLineHeight).css('font-size', newFontSize);
}
suggestions?
I made some mods to your code to get it to work on my end, I think it's cleaner and more efficient as well (see below). I haven't done a lot of testing but it seems to work in IE8 & FF.
IMO the line-height should adjust itself provided the line-height property is set to 'normal'. And I found that was exactly the case in Firefox. However, I did experience the problem you referenced in IE. In order to overcome it I had to replace the textarea with a clone of itself. Apparently, this forces IE to recalculate the proper line height. Hope this helps.
<script type="text/javascript">
$(document).ready(function () {
$("#plustext").click(function (e) { resizeText(1); e.preventDefault(); });
$("#minustext").click(function (e) { resizeText(-1); e.preventDefault();});
$("#resetfont").click(function (e) { $("#txtRegistryReportOuput").css('font-size', "14px"); e.preventDefault();});
});
function resizeText(multiplier) {
var textarea = $("#txtoutput");
var fs = (parseFloat(textarea.css('font-size')) + multiplier).toString() + 'px'; // Increment fontsize
var text = textarea.val(); // Firefox won't clone val() content (wierd..)
textarea.css({'font-size':fs}).replaceWith( textarea.clone().val(text) ); // Replace textarea w/ clone of itself to overcome line-height bug in IE
}
</script>
<div style="color: #0D1E28">
-
<a href ="#" id="resetfont">
<span style="font-size: 9px; letter-spacing: -3px;">A</span>
<span style="font-size: 16px;">A</span>
</a>
+
</div>
<textarea name="txtOutput" id="txtoutput" style="width: 600px; height: 550px; line-height: 8.5; overflow: auto; font-size: 21.5px;" rows="2" cols="20"></textarea>
This is one weird bug. By removing the node from the dom and re-inserting it, that seems to solve the problem.
$("#txtOutput").remove().appendTo("body");
http://jsfiddle.net/jyFfw/

How to remove "no file selected" from type=file inputs?

I can't seem to figure out any way to remove the "No file selected" text that shows up next to inputs of type "file".
Do you guys know any way how to remove this text?
input[type='file'] {
color: transparent;
}
Enjoy
There is no cross-browser way to do this. The "no file selected" text is in the implementation-defined part of the widget, and I don't believe that most browsers offer much in the way of browser-specific customization. On the other hand, you could simply use CSS to cover the text with something when the value attribute is empty.
You can do this by defining a width to the input and hiding the exceeding content (the undesired "No file selected" text).
input {
width: 132px;
overflow:hidden;
}
Here is the demonstration on jsfiddle.
Beware: each language has its own default text and it may render different input sizes. In brazilian portuguese that 132px width is fine!
My answer was based on this similar question on stackoverflow.
You can replace the file field with a button with the answer to this question: file upload button without input field?
CSS
<style>
#image_file{
position: relative;
width: 188px;
border: 1px solid #BBB;
margin: 1px;
cursor: pointer;
float: left;
}
</style>
HTML
<input id="image_file" onclick="getFile()" onfocus="this.blur()" value=""/>
<div style='height: 0px;width: 0px; overflow:hidden;'>
<input type="file" id="PinSpot_file">
</div>
<input type="button" onclick="getFile()" style="background-color: #DDD;" value="Browser" >
JAVASCRIPT
function getFile(){
document.getElementById("PinSpot_file").click();
}
// Event when change fields
$('#PinSpot_file').live('change', function(e) {
var file = this.value;
var fileName = file.split("\\");
document.getElementById("image_file").value = fileName[fileName.length-1];
//AJAX
}
This is a really good hack and its a lot cleaner.
HTML
<div id="file_info' style='display:inline;'>Browse</div>
<input type="file" name='file[]' multiple style='opacity: 0;' onchange='displayFileName()'/>
JS
function displayFileName() {
var files = $('input[type="file"]')[0].files;
document.getElementById('file_info').innerHTML = files.length + " images to upload";`
}
Well, since there is no way to completely disable the text, I'd suggest either placing an element over the text or try the following solution..
CSS
input[type="file"] {
width: 90px; /* Keep it under 100px in order to hide the unwanted text. */
}
and add an html inline-title attribute to the element to hide the "No File Chosen" hover text.
HTML
<input type="file" id="FileId" title="">
or, you could do it all with JavaScript.
JS
document.addEventListener('DOMContentLoad', myFunction);
function myFunction() {
const FilePicker = document.getElementById('FileId');
FilePicker.style.width = "90px";
FilePicker.title = ""; // Leave This Empty
}
You can try this. Its work for me firefox browser
<style type="">
input[type='file'] {
color: transparent;
}
</style>

Categories

Resources