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.
Related
I turned the input text-value into the inp1 var but once I want to call it inside the obj it doesn't work.
<input type="text" placeholder="Enter your text here" class="input fade-in" id="inp1" required>
var inp1 = document.getElementById("inp1").value;
$(function(){
$('#qrcode').qrcode({
width: 150,
height: 150,
text: "https://www.stackoverflow.com/" + inp1
});
});
I expect the qrcode code to show the url + the text of the input
Your code runs once, when the page loads. At that time, the input field is yet empty. Instead you probably want to update the qr code whenever the input changes. You need an event listener for that:
$(function(){
var input = $("#inp1"); // if you use jQuery, use it everywhere. Also retrieve the element when the document loaded
input.on("change", function() { // listen for input changes
$('#qrcode').qrcode({ // then update the qr code
width: 150,
height: 150,
text: "https://www.stackoverflow.com/" + input.val(),
});
});
});
You might want to consider using the input event instead of the change event depending on your usecase.
NOTE: I know this is similar to other questions, but for semantic and other reasons (e.g. ease of input on iOS) I specifically want the HTML input to be type="number". This is where the problem comes in....
I'm trying to set up an HTML form so that number fields show thousands commas -- e.g. "10,000,000" instead of "10000000". I want to set it so that the field displays the commas, but when it gets focus for actual editing the commas go away.
I can manually add commas to the value without any issue (I'm testing mainly in Firefox ~59); but any time I try to have JavaScript add the commas, the field is blanked out instead. Does anyone know how to make this work?
(Note, I'm using Numerals.js for formatting here... http://numeraljs.com/ )
Here is what I have:
$(document).ready(function(){
var numberFields = $("input[type=number]");
numberFields.each( function(){
$(this).val( numeral( $(this).val() ).format('0') );
});
numberFields.focus( function(){
$(this).val( numeral( $(this).val() ).format('0') );
});
numberFields.blur( function(){
$(this).val( numeral( $(this).val() ).format('0,0') );
});
});
Example HTML input:
<input name="myField" value="0" type="number">
(Incidentally -- and conveniently, I've confirmed that submitting a number with commas to the HTML form processing script just drops the commas and puts the unformatted number into the DB. Sweet!)
I'm not familiar with numeral.js, but if I were doing it, I would just save the numeric value as a data attribute, and then format with .toLocaleString, keeping in mind that you have switch between text and number types so that you can display your commas:
Seeing the issues with iOS, I believe the following will work. You can clone the element, THEN set the original to be a text input. Then, get the position of the original, and set the new element to be absolutely positioned over the original. Now, set the number input to opacity: 0, this way you won't see it, but when they click, it will click your clone. When the clone is clicked, set it to opacity: 1, and when it is blurred, set the original input to the cloned input's value, but using toLocaleString. I checked that it works in firefox, in theory it should work on iOS as well.
$(document).ready(function(){
var $clones = [];
var numberFields = $("input[type='number']");
numberFields.each(function(i){
var $clone = $(this).clone();
$(this).attr('type', 'text');
var destination = $(this).offset();
var width = $(this).width();
$clones.push($clone.css({
position: 'absolute',
top: destination.top,
left: destination.left,
opacity: '0',
width: width
}));
$(this).after($clone);
var that = this;
$clone.on('focus', function() {
$(this).css('opacity', '1');
});
$clone.on('blur', function() {
$(this).css('opacity', '0');
$(that).val('' + $(this).val() ? parseInt($(this).val()).toLocaleString() : '');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" pattern="[0-9,]*" />
NOTE: I'm leaving this original answer in case something here is useful down the road; but please see my other answer, which is a complete solution to the original question.
I've found no way to quite do what I want. Futzing with input "type" is too inconsistent in different browsers; and doesn't work anyway on iOS (which was 90% of the point). However, I did get "pretty close" working smoothly with the following. (NOTE this uses the numeral.js library for formatting):
JavaScript:
<script>
$(document).ready(function(){
var intFields = $("input[data-format=integer]");
intFields.each( function(){
$(this).attr( "pattern", "[0-9,]*" );
$(this).val( numeral( $(this).val() ).format('0,0') );
});
intFields.focus( function(){
$(this).val( numeral( $(this).val() ).format('0') );
});
intFields.blur( function(){
$(this).val( numeral( $(this).val() ).format('0,0') );
});
$("form#myForm").on( "submit", function(){
intFields.each( function() {
$(this).val( numeral( $(this).val() ).format('0') );
} );
return true;
} );
});
</script>
HTML:
<input type="text" data-format="integer" name="some_number" value="12345678>">
Overall, WAAAY too much work for such a common use-case. I hope browsers makers come up with a solution to this soon! There needs to be a simple, standard way to display numbers in fields.
My final function, based on Dave's answer. Dave's was not fully functional (though an effective proof of concept). This handles the name attribute (which is necessary for Form submit), and positions the input overlay relative to the original input, rather than the page (which prevents things going catywampus if the window is resized).
IMPORTANT: When using this, you must use <label>...</label><input>, NOT <label>...<input></label> for your number fields Fixed!:
$(document).ready(function() {
format_integers();
});
/**
* Any form inputs with type=number and data-format=integer will display contents with commas when input not in focus.
* #param container string to be used as jQuery search. Defaults to 'body'; but can be any specific element
*/
function format_integers(container) {
container = (typeof container !== 'undefined') ? container : 'body';
var $wrapper = $('<span>').css({
position: 'relative',
display: 'inline-block',
padding: 0
});
$(container + " input[type='number'][data-format=integer]").each(function() {
var $clone = $(this).clone();
var $parentLabel = $(this).parent('label');
if( $parentLabel.length !== 0 ) {
$parentLabel.css( 'display', 'inline-flex' );
$clone.css( 'order', 1 );
$(this).css( 'order', 2 );
}
$(this).wrapAll($wrapper).css({
position: 'absolute',
top: 0,
left: 0,
opacity: 0
})
.attr('pattern', '[0-9]*');
$clone.removeAttr('name class id pattern')
.attr('type', 'text')
.attr('tabindex', -1)
.css('width', $(this).width)
.val($(this).val() ? parseInt($(this).val()).toLocaleString() : '');
$(this).before($clone);
$(this).on('focus', function() {
$(this).css('opacity', '1');
});
$(this).on('blur', function() {
$(this).css('opacity', '0');
$clone.val($(this).val() ? parseInt($(this).val()).toLocaleString() : '');
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label>Integer Input: <input type="number" data-format="integer" name="test" id="num_input" value="123456789" /></label><br>
<label for="num_input2">Integer Input: </label>
<input type="number" data-format="integer" name="test2" id="num_input2" value="10000000" /><br>
<label>Textarea <textarea>Something to focus other than the number fields</textarea></label>
</form>
What I'm going after is a code that will gather all my text input fields and detect whether or not they have any input. If so I'd like for there to be a glow effect added, if they're left empty or they delete the data and leave it empty I'd like for the glow effect to turn off.
So far from everything I've found this is what I came up with so far, it doesn't work of course, but it's the best I could try to rationalize.
function glow(){
var text = document.getElementsByClassName('tex_inp01 tex_inp02');
if (text.value ==null){
text.style.boxShadow="#8fd7d2 0px 0px 22px";
}
else
remove.style.boxShadow;
}/**function**/
I used the .getElementsByClassName because the getElementsById didn't support multiple IDs as it seems, but if there's another more efficient way of gathering them all please share.
Simple solution can be adding class having glow with javascript:
var text = document.getElementsByClassName('tex_inp01 tex_inp02');
text[0].className = text[0].className + " glow";
DEMO
Note: If you want to add glow class to each input then you have to iterate through loop and add class to each element. Because text is
HTMLCollection of elements.
You need to get the value of each element, not of the HTMLCollection returned by document.getElementsByClassName; Array.prototype.forEach can help with this. Then, a value can’t be null, but empty.
Edit: Wait a minute… you want the glow effect if the element has an input, right? Then your if-else statement is the wrong way around.
This is the correct function:
function glow() {
"use strict";
Array.prototype.slice.call(document.getElementsByClassName("tex_inp01 tex_inp02")).forEach(function(a) {
if (a.value !== "") {
a.style.boxShadow = "0px 0px 22px #8fd7d2";
}
else {
a.style.boxShadow = "";
}
});
}
You have a couple of mistakes in your existing code (as presented in the question): (1) text.value ==null - do not check against null, because an inputs value will never be a null. Check its length. (2) remove.style.boxShadow; - I think that was a typo. It should have been text.style.boxShadow = 'none'.
..to be a glow effect added, if they're left empty or they delete the
data and leave it empty I'd like for the glow effect to turn off..
You can check if the input has been left empty by simply checking the length of the value. However, to check if the input has been entered and then deleted you will have to keep a flag to keep track of that. You can do that by hooking up the change event on inputs and then setting a flag via data attribute. Later when you are checking each input for applying a style, along with the length also check this attribute to see if the input was edited out.
Here is a simple example putting together all of the above (explanation in code comments):
var inputs = document.getElementsByClassName("a b"), // returns a collection of nodelist
button = document.getElementById("btn"); // just for the demo
button.addEventListener("click", checkInputs); // handle click event on button
[].forEach.call(inputs, function(elem) { // iterate over all selected inputs
elem.addEventListener("change", function() { // handle change event
this.setAttribute("data-dirty", true); // set a data attribute to track..
}); // .. a flag when it is changed
});
function checkInputs() {
[].forEach.call(inputs, function(elem) { // iterate over selected inputs
var isDirty = elem.getAttribute("data-dirty"); // check the dirty flag we set
if ((elem.value.length > 0) || (isDirty)) { // if empty or changed
elem.style.boxShadow = "none"; // reset the style
} else {
elem.style.boxShadow = "#f00 0px 0px 5px"; // else apply shadow
}
});
}
<input class="a b" /><br /><br /><input class="a b" /><br /><br />
<input class="a b" /><br /><br /><input class="a b" /><br /><br />
<button id="btn">Check</button>
If you wanted to validate the inputs while the user is typing, you can use keyboard events to check the value of the input(s):
document.querySelector('input[type="text"]').addEventListener('keyup',
function(event){
var element = event.target;
if (element.value.trim() === '') {
element.classList.add('empty');
} else {
element.classList.remove('empty');
}
});
See fiddle for example: http://jsfiddle.net/LrpddL0q/.
Otherwise this could be implemented the same way without the addEventListener to perform as a one-off function.
Jquery can help you as the following
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function () {
$(".MyInput").bind('keypress', function () {
$('.MyInput').css("boxShadow", "#8fd7d2 0px 0px 22px");
});
$(".MyInput").bind('keydown', function () {
if ($(".MyInput").val() == "") {
$('.MyInput').css("boxShadow", "none");
}
});
});
</script>
HTML:
<input type="text" value="" class="MyInput" />
this code working only online If you need to download Jquery library visit this
https://jquery.com/download/
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'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(...)