add .00 at the end of value while typing - javascript

I'm working a simple field where only accepts numbers, what I want is to add ".00" at the end of the value while I'm typing. ex. 1000.00.
the problem I cant achieve that format, after 1 digit it adds '.00' and cant type anymore.
I tried the answer here but didn't work.
here is my sample work
$(document).ready(function(){
$("input").keyup(function(){
var val = parseInt($(this).val());
$(this).val(val.toFixed(2));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
Hope you can help me.
Thanks.

Use blur function like this:
$("input").blur(function(){
var val = parseInt($(this).val());
if(val){
$(this).val(val.toFixed(2));
}else{
$(this).val(0);
$(this).focus();
}
});

If what you want to do is type 1 and immediately get 1.00, then type 2 and you will get 12.00, then you need to save cursor position (like described here).
So you want to get current cursor position
format the input data
update input element
restore cursor position in needed place (depending on where it should be moved)

Try this:
$( 'input' ).on( 'input', function() {
var val = $( this ).val(),
arr = val.split( '.' );
if ( arr.length > 1 )
$( this ).val( arr[ 0 ] + val.substr( val.length - 1 ) + '.00' )
else
$( this ).val( val + '.00' )
} ).on( 'keypress', function( e ) {
return e.charCode == 46 || ( e.charCode >= 48 && e.charCode <= 57 )
} )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

i think you should try focusout event..
$(document).ready(function(){
$("input").focusout(function(){
var val = parseInt($(this).val());
$(this).val(val.toFixed(2));
});
});

Related

not receive negative numbers

I have the following code: http://jsfiddle.net/ntywf/1987/
$(document).ready(function () {
$('input').keyup(function() {
var $th = $(this);
$th.val($th.val().replace(/[-]/g, function(str) {
//alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.');
return '';
}));
});
});
what I want is to remove the "-" sign off when it is inserted. what happens is that the cursor is always the last decimal home. I just want this code not to let the user enter negative numbers. How can I do this? (the problem is to move the cursor within the input, since it is always sent to the last character)
You can use a KeyCode (Link) to verify what key you pressed, and use replace to remove it:
$('input').keyup(function(e) {
var code = e.keyCode || e.which;
if(code == 109 || code == 189) { //Enter keycode
//Do something
var valor = $(this).val();
$(this).val(valor.replace(/[-]/g, ''))
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text"/>
Here what I have tried.
JS
$('input').keyup(function() {
var $th = $(this).val();
$th = $th.replace(/[-]/g, "");
$(this).val($th)
console.log( $(this).val());
});
It will remove - sign from data.
This should solve your problem
What I have done is:
I have used the inbuilt HTML input field method setSelectionRange(), which sets the start and end positions of the current text selection in an element. (From MDN)
MDN Reference : https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange
JS Code:
$(document).ready(function () {
$('input').keyup(function() {
var $th = $(this);
$th.val( $th.val().replace(/[-]/g, function(str) {
//alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.');
return '';
} ) );
$('input')[0].setSelectionRange(0, 0); //this method sets the range to zero text starting from 0 index to 0 index
});
});
JSFiddle: http://jsfiddle.net/dreamweiver/ntywf/1998/
Use type = "numeric" and min="0" This way you can prevent your text-field from accepting alphabets as well. min=0 will always make sure that it will never accept -ve value.
<input type="number" min="0"/>
JSFIDDLE DEMO will be helpful to you.

Can we use a constructed dynamic jQuery selector?

I want to contruct a jquery selector as a string and pass its value to the selector.
$(document).on( 'keyup', function( e ) {
if( e.keyCode == 9 ) {
//console.log( e.target );
console.log(e.target.id);
var preTabIndex = document.getElementById(e.target.id).tabIndex;
var nextTabIndex = preTabIndex + 1;
console.log(preTabIndex);
console.log(nextTabIndex);
//console.log($('[tabindex=3]')[0].id);
var selector = "[tabindex=" + nextTabIndex + "]";
console.log(selector);
console.log($(selector)[0].Id);
//document.getElementById($("[tabindex=3]")[0].id).focus();
document.getElementById($(selector)[0].id).focus();
}
} );
Can this be done? I couldn't find it on my initial googling.
With this i am getting an undefined when i do
console.log($(selector)[0].Id);
Yes, you can. Make sure you use the . or # to denote the target. For example,
In your HTML:
<p id="header">hello</p>
In your JS:
var my_selector = "#header";
$(my_selector).html('wow');

Catching ⌘+1 in Safari JavaScript

I'm writing a Safari 6 extension which adds a few keyboard shortcuts. One of the things I'd like to do is catch when the user presses ⌘+1 ⌘+2, etc. Right now, Safari seems to not fire any event when this happens. Here's a Fiddle: http://jsfiddle.net/Xe9YQ/ to show the code, and here's the JS:
$( 'body' ).bind( 'keypress', function ( event ) {
var modifier = '';
if ( event.metaKey ) {
modifier += 'cmd-';
}
if ( event.ctrlKey ) {
modifier += 'ctrl-';
}
if ( event.altKey ) {
modifier += 'alt-';
}
if ( event.shiftKey ) {
modifier += 'shift-';
}
$( 'body' ).html( modifier + event.keyCode );
});
If you try "⌘+j", "⌘+t", or even "⌘+0" and "⌘+shift+5" you'll see correct output. From this, it seems that it's not a problem of overriding browser shortcuts, and not a problem of using the numerical row.
Is anyone familiar with this problem? Is this a known bug? I'd appreciate any advice.
You have to use the keydown event in combination with preventDefault(), because ⌘ combinations may have bindings already (in Chrome, for example ⌘ + 1 switches to the first tab).
$( 'body' ).bind( 'keydown', function ( event ) {
var modifier = '';
if ( event.metaKey ) {
event.preventDefault();
modifier += 'cmd-';
}
if ( event.ctrlKey ) {
modifier += 'ctrl-';
}
if ( event.altKey ) {
modifier += 'alt-';
}
if ( event.shiftKey ) {
modifier += 'shift-';
}
$( 'body' ).html( modifier + event.keyCode );
});

Use jQuery to switch between left and right text-alignment, depending on the language

I have input boxes and textareas that need to be toggled between left-alignment and right-alignment (depending on the user's language, the direction would be different). How can I do this with jQuery?
As I don't know the key code for all Persian letters, I had to do it like this:
var str = $('#item').val(); //this is your text box
var firstChar = str.substr(0,1);
var characters = ['ا','ب','پ','ت','س','ج','چ','ح','خ','د','ذ','ر','ز','ژ','س','ش','ص','ض','ط','ظ','ع','غ','ف','ق','ک','گ','ل','م','ن','و','ه','ی'];
function checkPersian() {
var result = false;
for (i = 0 ; i<32 ; i++) {
if (characters[i] == firstChar) {
result = true;
}
}
return result;
}
if (checkPersian()) {
$('#item').css('direction','rtl');
} else {
$('#item').css('direction','ltr');
}
Here I have completely overhauled Mohammad's script but it's limited to its purpose: scanning if the first letter the user types in is Persian and changing the inputs direction according.
Here it is: jsfiddle.net/uPH7N/4
You can use dir="auto" attribute in modern browsers: Live Demo
<input type="text" dir="auto"><br>
Also you can do it by jQuery like this: Live Demo
$('input, textarea').keyup(function() {
$(this).val().charAt(0).charCodeAt(0) < 200 ? $(this).css('direction','ltr') : $(this).css('direction','rtl');
});
Toggle the elements' css with jquery (assuming the relevant inputs/textareas all have the class textdirectionBoxes):
$('.textdirectionBoxes').css('direction', 'rtl');
and
$('.textdirectionBoxes').css('direction', 'ltr');
What about
jQuery( document ).ready( function(){
var language = navigator.userLanguage || navigator.language;
if( jQuery.inArray( language, ['ar', 'he', 'ur'] ) != -1 )
jQuery( 'input[type="text"], input[type="password"], textarea' ).css( 'direction', 'rtl' );
});
?
edit: fixed little code-bug
function isUnicode(str) {
return (str.charCodeAt(str.length-1) > 255) ? true : false;
}
$('input[type=text]').each(function() {
$(this).keyup(function(e) {
$(this).css('direction',
isUnicode($(this).val()) ? 'rtl' : 'ltr'
);
});
});

Check First Char In String

I have input-box. I'm looking for a way to fire-up alert() if first character of given string is equal to '/'...
var scream = $( '#screameria input' ).val();
if ( scream.charAt( 0 ) == '/' ) {
alert( 'Boom!' );
}
It's my code at the moment. It doesn't work and I think that it's because that browser doesn't know when to check that string... I need that alert whenever user inputs '/' as first character.
Try this out:
$( '#screameria input' ).keyup(function(){ //when a user types in input box
var scream = this.value;
if ( scream.charAt( 0 ) == '/' ) {
alert( 'Boom!' );
}
})
Fiddle: http://jsfiddle.net/maniator/FewgY/
You need to add a keypress (or similar) handler to tell the browser to run your function whenever a key is pressed on that input field:
var input = $('#screameria input');
input.keypress(function() {
var val = this.value;
if (val && val.charAt(0) == '/') {
alert('Boom!');
}
});

Categories