I'm using a text box like the following and I want that the text box width will be according to the size of the text inside, it that possible?
#Html.TextBoxFor(model => model.Name, new { disabled = "disabled" })
An easy answer for your problem is(using some jquery):
<script>
$(document).ready(function () {
$('.txt').css('width', (($('.txt').val().length)+1) * 7 + 'px'); //You can increase or decrease multiplication factor i.e '7' here as required.
});
</script>
#Html.TextBoxFor(model => model.Name, new { disabled = "disabled",#class="txt" })
DEMO Link :- http://jsfiddle.net/Lbaf8cek/5/
Not for this question because here textbox is disabled but if textbox is not disabled then most easiest way to adjust textbox width is :
<input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';">
Fiddle Link :-http://jsfiddle.net/kartikeya/1vnw7d44/
UPDATED WITH CODE EXPLANATION:
here you go, the input will always be as long as its characters, whether you type, remove or give it a value before running the script: DEMO
//this is a plugin snippet (or function) to check if the element has
//horizontal scrollbar
$.fn.hasHorizontalScrollBar = function() {
if (this[0].clientWidth < this[0].scrollWidth) {
return true
} else {
return false
}
}
//the end of plugin
var originalWidth=$('.txt').width(); //we store the original width
//(the width of the input at the page load) in a variable to use it as a
//measurement in order to not let the input get smaller than this size
//this function checks the width of `.txt` (the input) to see if it has
//horizontal scrollbar or not, if it does then expands the width of the input to
//the scroll size, else it checks to see if the width is added to the
//original width, if so, removes one character (depending on the font size it'll
//change - here it is 7 px)
function changeWidth(){
if($('.txt').hasHorizontalScrollBar()){
$('.txt').width(document.getElementsByClassName('txt')[0].scrollWidth);
}
else if(originalWidth<$('.txt').width()){
$('.txt').width($('.txt').width()-7);
}
};
//end of the function
changeWidth(); //run the function at page load, to give the input a size as wide as its
// character's length
$('.txt').keydown(changeWidth); //assign the function to the keydown event of the input
//so whenever a character is added or removed the function will run again
This post handles the same topic I believe: Growing text box based on width of characters input
Since you're using mvc and the textbox is disabled for edits, you could try:
#Html.TextBoxFor(model => model.Name, new { disabled = "disabled", length = Model.Name.Length() })
Sorry if my syntax is incorrect but I don't have an IDE up atm. But what you're doing is setting the textbox length to the number of characters of the input. This should effectively set the textbox to the correct length. Unless you have some css rules applied somewhere.
UPDATE:
Another way (like below) is by using Javascript, this way you can widen or shorten your textbox dynamically based on input. But preferably, when it's only for displaying the name, you should try #Html.DisplayFor(...)
Related
My function, addthisTxt, is not checking the length. It should not exceed 11. Below is what I have tried so far; I'd like to keep on adding text until it reaches the max length, otherwise it should restrict the user from adding more.
HTML
<input type="checkbox" name="chkbxr" value="add this offer on wrapper"
(change)="addthisTxt($event.target.getAttribute('txt'), $event.target.checked)">
JavaScript
addthisTxt(txt, checked): void {
if (checked) {
if((this.v.offerName.length +txt.length) >= 55){
this.v.offerName = this.v.offerName + txt;
}
this.v.offerName = this.v.offerName;
}
}
You are setting the value on this.v.offerName. The UI element is not bound to this JavaScript variable and you need to set the value of the UI input element to restrict the value.
I want to append various things to an input with buttons.
button#addNumber -> appends 245
button#addOperation -> appends +
A problem arises with button#radicSign.
I want to add the template for a square root sqrt() and place the caret inside the parentheses afterwards for the user to type in the number.
Is this possible?`
If yes, is it worth the effort? Or should I open a dialog box and insert it then?
$('button#radicSign').on('click', function add2digit() {
addOperation('sqrt');
});
function addOperation(op) {
var problemInput = $('input#testProblem');
problemInput.val(problemInput.val() + op);
}
You should be able to do something like this to achieve what you want:
$('#sqrt').click(function() {
var length = $('#a').val().length;
$('#a').val($('#a').val()+'sqrt()');
$('#a').focus()[0].setSelectionRange(length+5, length+5);
});
JSFiddle
I have a textbox where the user can enter any number of characters, But I want its width to be increased dynamically with respect to the number of characters entered into it.
I have done a workaround shown below and it works partially, it will increase the width dynamically but not so precisely and will hide the first entered characters after a while because of my poor logic applied in it. I've just given a wild cutoff of 17 characters count to start the increment.
It should start the width increment only if the character count reaches the end of textbox.
UPDATE:
I am looking to make visible all the characters entered in the field, whereas in default the text box hides the leftmost characters.
FIDDLE DEMO
HTML
<input type="text" id="txtbox" />
SCRIPT
$('#txtbox').keypress(function() {
var txtWidth = $(this).width();
var cs = $(this).val().length;
if(cs>17){
$(this).width(txtWidth+5);
}
});
I have tried this code and it works fine.
<html>
<head>
<script type="text/javascript">
function Expand(obj){
if (!obj.savesize) obj.savesize=obj.size;
obj.size=Math.max(obj.savesize,obj.value.length);
}
</script>
</head>
<body>
<form>
<input type="text" size="5" style="font-family:Courier;" onkeyup="Expand(this);">
</form>
</body>
</html>
Be sure to use mono space fonts in text box, otherwise the size attr. and number of characters won't match
Adding a simple inline code in onkeyUp should help
<input type="text" name="fname" onkeypress="this.style.minWidth = ((this.value.length + 1) * 7) + 'px';">
<input type="text" id="txtbox" size="10"/>
$('#txtbox').keypress(function() {
var txtWidth = $(this).attr('size');
var cs = $(this).val().length-6;
txtWidth = parseInt(txtWidth);
if(cs>txtWidth){
$(this).attr('size',txtWidth+5); }
});
You were using width field which is actually meant for type = image.
You can get more info here.
I have used size attribute which is used to set the size of input tag in pixels. When its 1 it can take 6 characters by default hence -6. Hope it helps.
A solution similar to #Tejas', but doesn't require the font to be mono-space:
The trick is to use scrollWidth, which gives us the total string length, even on single-line textboxes without a scrollbar:
https://stackoverflow.com/a/9312727/1869660
NOTE: I couldn't get this to work in IE, where scrollWidth always returned 2 for some reason..
Some code:
function expand(textbox) {
if (!textbox.startW) { textbox.startW = textbox.offsetWidth; }
var style = textbox.style;
//Force complete recalculation of width
//in case characters are deleted and not added:
style.width = 0;
var desiredW = textbox.scrollWidth;
//Optional padding to reduce "jerkyness" when typing:
desiredW += textbox.offsetHeight;
style.width = Math.max(desiredW, textbox.startW) + 'px';
}
...
<input type="text" onkeyup="expand(this);" >
JSFiddle example
On the x-editable documentation you can find the option type so i guess you have to add data-editable-type="textarea"
I have two input fields, where people can write numbers. And what I need is when a person finished writing in this input field some constant words or symbols are left there near his number.
I think that you didn't get anything from what I wrote above so I will try to explain with this example:
In the upper there are two inputs you see what person printed himself. And two inputs in the bottom are what he gets when he puts his cursor out of the input where he was printing.
(I don't need all four inputs, just two...upper two just show the first step and bottom two show the final step)
I think it can be done by javascript... but I couldn't do it by myself and I couldn't find anything in web...
You'll need to get a reference to the textbox (try onblur event) and then append your static text to the value property.
I've used the following before, the reason I chose using an image over anything else was because text added to an input dynamically can cause confusion, as well as getting in the way when users wish to edit. Using an image meant it could be constantly there and wouldn't get in the way of the user typing:
It's only written in jQuery because it was lying around, this could easily be rewritten in pure js - and it could easily be optimised.
http://jsfiddle.net/pafMg/
css:
input {
border: 1px solid black;
background: #fff;
padding: 2px;
}
markup:
<input class="right-aligned" type="text" />
<input class="left-aligned" type="text" />
code:
In the following code the padding-left and padding-right has to take into account the width of the image you use.
$(function(){
/* For left aligned additions */
$('input.left-aligned')
.css({
'padding-left': '20px',
'background-image': 'url(/favicon.png)',
'background-position' : '2px center',
'background-repeat': 'no-repeat'
});
});
The left aligned version is really simple, the right aligned gets a little bit more complex however:
$(function(){
/* For right aligned additions */
$('input.right-aligned')
.bind('keypress keyup', function(e){
var input = $(this), measure, text = input.val(), x, w, y;
/// You can calculate text width, but it's not easily cross-browser
/// easier method, inject the text to a span and measure that instead
if ( !input.data('measure') ){
/// only build our measuring span the first time
measure = $('<span />')
.hide() // hide it
.appendTo('body')
/// try and match our span to our input font
/// this could be improved
.css({
'font-weight':input.css('font-weight'),
'font-family':input.css('font-family'),
'font-size':input.css('font-size')
});
/// store the measure element for later
input.data('measure', measure );
}
/// handle if the user types white space
text = text
.replace(/\s/g,' ')
.replace(/</g,'>');
measure = input.data('measure');
measure.html(text);
w = measure.width();
y = input.width();
/// calculate the image position (minus padding)
x = w + parseInt(input.css('padding-left')) + 2;
/// take into account the scroll ability of an input
x -= ( w > y ? w - y : 0 );
/// reposition our image background on the input
input
.css({
'padding-right': '20px',
'background-image': 'url(/favicon.png)',
'background-position' : x + 'px center',
'background-repeat': 'no-repeat'
});
}).trigger('keyup');
});
Take a look at the blur event using jQuery: http://docs.jquery.com/Events/blur#fn
Here's a quick sample: http://jsfiddle.net/jDGg9/
<form>
Field 1: <input id="ip1" type="text" value="" />
Field 2: <input id="ip2" type="text" value="" />
</form>
$('#ip1').blur(function() {
$('#ip1').val($('#ip1').val() + ' month');
});
$('#ip2').blur(function() {
$('#ip2').val($('#ip2').val() + ' month');
});
Since you didn't specify using jQuery, here's a simple example with basic Javascript using the blur event (as everyone has already specified) although it might make sense to use the onchange event:
http://jsfiddle.net/A9yVv/1/
<input type="text" id="text1" value="" />
<br />
<input type="text" id="text2" value="" readonly="readonly" />
var text1 = document.getElementById("text1");
text1.onblur = function () {
var text2 = document.getElementById("text2");
text2.value = this.value + " month(s)";
};
If jQuery is available this will be much easier, but the code can be rewritten to work without it if it's not.
When an input loses focus, the blur event is fired, and when it regains focus the focus event is fired. If you store the original value (say, using jQuery's data method), you can accomplish what you're asking fairly easily:
<input type="text" name="months" class="month" />
<input type="text" name="price" class="price" />
<script>
jQuery(function($) {
$('.months')
.blur(function(event) {
// This code runs when the input with class "months" loses focus
var originalValue = $(this).val();
$(this)
.data('original-value', originalValue)
.val(originalValue + ' months');
})
.focus(function(event) {
// This code runs when the input with class "months" gains focus
var originalValue = $(this).data('original-value');
if (typeof originalValue !== 'undefined') {
$(this).val(originalValue);
}
});
$('.price')
.blur(function(event) {
// This code runs when the input with class "price" loses focus
var originalValue = $(this).val();
$(this)
.data('original-value', originalValue)
.val('$ ' + originalValue);
})
.focus(function(event) {
// This code runs when the input with class "price" gains focus
var originalValue = $(this).data('original-value');
if (typeof originalValue !== 'undefined') {
$(this).val(originalValue);
}
});
$('form.myform')
.submit(function(event) {
// This code runs when the form is submitted
// Restore the original values, so they are submitted to the server
$('.months').val($('.months').data('original-value'));
$('.price').val($('.price').data('original-value'));
});
});
</script>
I've done it all without javascript... The problem was that it changed the value of the input field but I didn't need that.
So I've just made images of '$' and 'month' and added them as a background in CSS to the inputs... In the first input field i wrote a property maxlenth='3' so numbers won't be written over the constant text and in the second field I've done padding-left='15px' in CSS.
Thanks everyone.
https://auth.me.com/authenticate
On this website when you type in your email address , the font-size will automatically be reduced if the email address fills the box size.
How can we do the same using Javascript?
which are the events that are being fired / captured ?
$("input").keypress(function(){
if(this.value.length>43)//or some other value
{//do stuff here
}
});
Keydown is what you are looking for
I have made a library, named resize.js, which allow to write:
<input type="text" resize="true" />
This is the library:
var precision=18;
window.onload=function()
{
for(var i=0,t=document.getElementsByTagName("input"),l=t.length;i<l;i++)if(t[i].getAttribute("resize")==="true")
{
var div=document.createElement("div");
div.setAttribute("style","font-size"+parseInt(t[i].s("font-size"))+";font-family:"+t[i].s("font-family")+";position:absolute;top:-10000px;left:-10000px;");
document.body.appendChild(div);
(function(i,div,min,max,dif,l,r,w,h,pre){setInterval(function(){modify(t[i],div,min,max,dif,l,r,w,h,pre);},100);})
(
i,
div,
t[i].getAttribute("min")||parseInt(t[i].s("font-size"))-3,
t[i].getAttribute("max")||parseInt(t[i].s("font-size")),
parseInt(t[i].s("padding-left"))+parseInt(t[i].s("padding-right"))+parseInt(t[i].s("border-left-width"))+parseInt(t[i].s("border-right-width"))+precision,
parseInt(t[i].s("padding-left")),
parseInt(t[i].s("padding-right")),
t[i].offsetWidth,
t[i].offsetHeight,
precision
);
}
}
Object.prototype.s=function(p)
{
return this.currentStyle?this.currentStyle[p]:document.defaultView.getComputedStyle(this,null).getPropertyValue(p);
}
function modify(el,c,min,max,dif,l,r,w,h,pre)
{
el.style.width=w+"px";
el.style.height=h+"px";
c.innerHTML=el.value.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/ /g," ");
var test=c.offsetWidth;
while(test>=el.offsetWidth-dif&&parseInt(el.s("font-size"))>min)
{
el.style.fontSize=parseInt(el.s("font-size"))-1+"px";
c.style.fontSize=el.style.fontSize;
test=c.offsetWidth;
}
while(test<el.offsetWidth-dif&&parseInt(el.s("font-size"))<max)
{
el.style.fontSize=parseInt(el.s("font-size"))+1+"px";
c.style.fontSize=el.style.fontSize;
test=c.offsetWidth;
}
if(parseInt(el.s("font-size"))===min&&c.offsetWidth>el.offsetWidth-dif)
{
el.style.paddingLeft="0px";
el.style.paddingRight="0px";
}
else
{
el.style.paddingLeft=l+"px";
el.style.paddingRight=r+"px";
}
}
A fiddle: http://jsfiddle.net/mageek/GEp2y/1
Some advices:
If the attribute "resize" equals anything other than true, or is not set, the text-box will behave as a normal text-box.
You can set the maximum font-size and the minimum font-size allowed by setting the "max" and the "min" attributes. By default, the maximum is the current font-size and the minimum is 3 sizes smaller than the maximum.
I added something, like https://auth.me.com/authenticate, which removes the padding to gain space when the minimum font-size is reached.
There is the variable 'precision' (at the beginning of resize.js) that depends on the text-box, I set it to 18 for default text-box but if you modify the style of the text-box, you will maybe have to modify the variable to a better value (by testing).
I don't ensure the host of resize.js on the website like in the fiddle, you should copy the source code in a new file and save it.
I've made the code for you, I took for example what I did on my own website for the contact form: the <textarea> gets taller if there is lot's of text.
The thing to do is to create an invisible<div>, for each keydown in the <input>, take its content and puts it into the <div>, and check its width is bigger than the <input>'s one.
The HTML
<form>
<input>
<div></div>
</form>
The CSS where we set the same font-size for the <input> and the <div> and hide the <div> (with position: absolute because we need it's width and we don't want it to change the layout)
form > * {
font-size: 22px
}
form > input {
width: 150px;
font-size: 18px;
}
form > div {
position: absolute;
left: -10000px;
}
And the JavaScript (with jQuery here)
var $form = $('form')
, $input = $('input', $form)
, $autoResize = $('div', $form)
, $both = $input.add($autoResize)
, fontSize = parseInt($input.css('font-size'), 10)
$input.on('keydown', function() {
$autoResize.html(this.value.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/ {2,}/g, function(spaces) {
// Change the spaces to $nbsp; except the last one
for (var i = 1, fakeSpaces = '', space; space = spaces[i++];) {
fakeSpaces += ' '
}
return fakeSpaces + ' '
})
)
// We add 10px to be sure it doesn't stick to the edges
if ($autoResize.outerWidth() >= $input.outerWidth() - 10) {
do {
$both.css('font-size', --fontSize)
} while ($autoResize.outerWidth() >= $input.outerWidth() && fontSize > 10)
// 10px is the smallest font-size accepted
if (fontSize === 10) {
$input.off('keydown')
}
}
})
Here is the jsFiddle.
You must use JavaScript to count how much characters've been typed already (I believe with .change() in jQuery) and change the font-size accordingly.
Yes,I think what #somebody is in trouble is doing is what they are doing in here.
Calculate how many letters will fit into the box - you know the width of the textbox. You know the font-size & padding that is being given here. So you know how many letters can be typed in the textbox before it overflows( not exactly) .
Or you can just type random letters & see how many can fit ! :)
Well, if you have time, you can as well dive into the events being fired when you keydown on the email address text box. You will learn a lot!