Jquery Removing '0' in textbox after any value is entered - javascript

Here is my Fiddle
Initially the textbox won't have any value.
If any value is entered and it was emptied '0' will be added in it.
But the '0' is not removed after entering any value to it.
How can i remove the '0' if any value is entered it.
Here is my Code :
$('.qty').keyup(function(){
if($(this).val() == ""){
$('.qty').val('0');
}else if($(this).val() > 0){
$(this).val().replace(0,'');
}
});

Instead of
$('.qty').val('0');
Add palceholder.
$('.qty').attr('placeholder','0');

Try This Code:
$('.qty').keyup(function(){
if($(this).val() == ""){
$('.qty').val('0');
}else if($(this).val() > 0){
console.log($(this).val());
$(this).val().replace(0,'');
}
if($(this).val()!=0){
var text = $(this).val();
alert(text.slice(0,1));
if(text.slice(0,1)==0)
{
$(this).val(text.slice(1,text.length));
}
}
});
Working Demo

If placeholder isn't an option, you could parse value to integer:
$('.qty').keyup(function(){
var val = parseInt(this.value, 10);
this.value = val ? val: 0;
});

.replace() returns the modified string, you need to store it back into the value. Try this:
$('.qty').keyup(function () {
if ($(this).val() == "") {
$('.qty').val('0');
} else if ($(this).val() > 0) {
console.log($(this).val());
$(this).val(function() {
return this.value.replace(/^0+/, '');
});
}
});
I've also changed the replace() call to use a regular expression, so it only removes zeroes at the beginning of the input. Otherwise, it will change 102 to 12.
fiddle

You could achieve this using blur and focus instead of keyup :
$('.qty').blur(function() {
if (this.value == '') this.value = '0';
}).focus(function() {
if (this.value == '0') this.value = '';
});
JSFiddle example

Try this..
<input type="text" name="test" value="0">
$(document).ready(function(){
var Input = $('input[name=test]');
var value= Input.val();
$(Input).focus(function() {
if($(this).val() == value)
{
$(this).val("");
}
}).keyup(function(){
if($(this).val().length == 0)
{
$(this).val(value);
}
});
})

Try like this,
$('.qty').keyup(function(){
if($(this).val() == ""){
$('.qty').val('');
}else if($(this).val() > 0){
console.log($(this).val());
$(this).val().replace(0,'');
}
});

Instead of replace 0, replace with whole value using javascript Number function
$('.qty').keyup(function(){
if($(this).val() == ""){
$('.qty').val('0');
}else if($(this).val() > 0){
console.log($(this).val());
$(this).val(Number($(this).val()))
}
});
refer jsFiddle

Related

Jquery: check if variable is defined after keyup() function

Am creating register form with jquery function keyup(),
for example if input is correct I assign it to a txtuname variable,then I press register button and I need to know that all form variables are correct and defined.Code below is not working:
<script type="text/javascript">
$("document").ready(function() {
$("#txtuname").keyup(function() {
if ($("#txtuname").val().length < 6) {
jQuery("label[for='txtuname']").text("user name is too short");
}
if ($("#txtuname").val().length >= 6) {
var txtuname = $("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function() {
if (typeof txtuname == 'defined') {
alert("defined");
}
if (typeof txtuname == 'undefined') {
alert("undefined");
}
});
});
</script>
Modified code. Main point of this code is that txtuname should be visible in both scopes of keyup event listner and click listner. So if there are more lements, create Validation object and just check whether all the values was set and correct. And yes, use or $ or jQuery in your code.
$("document").ready(function(){
var txtuname = null;
$("#txtuname").keyup(function(){
if($("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if($("#txtuname").val().length>=6){
txtuname=$("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function(){
if( txtuname == null || txtuname.length < 6) ){
alert("incorrect");
}
else{
alert("correct");
}
});
});
Updated check of variable using comment of #Rhumborl , thx
Replace code with below condition -
if( typeof txtuname !== 'undefined' && txtuname.length >= 6) ){
//proceed further
}else{
alert('Please correct entries.');
return false;
}
I would put the validation logic in a function and call that, you can update this with your specific requirements and only do it once:
function isValidName(field) {
var myName = field.val().trim();
// some of this is redundant but just to show possibilities
var isValid = myName.length && myName.length >= 6 && myName && undefined !== myName && myName != " ";
var myLabel = $("label[for='" + field.attr('id') + "']");
if (isValid) {
myLabel.text("");
} else {
myLabel.text("user name is too short");
}
return isValid;
}
$("document").ready(function() {
$("#txtuname").keyup(function() {
isValidName($(this));
});
$("#submitRegistration").click(function() {
var nameIsValid = isValidName($("#txtuname"));
if (nameIsValid) {
alert("valid");
} else {
alert("undefined or invalid");
}
});
});
You are using $ as well as jQuery window.jQuery object in your code. Do not use both at time , you can check by both
jQuery("document").ready(function() { jQuery("#txtuname").keyup(function(){ if(jQuery("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if(jQuery("#txtuname").val().length>=6){
var txtuname=jQuery("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
jQuery("#submitRegistration").click(function(){
if(typeof txtuname =='defined'){
alert("defined");
}
if(typeof txtuname =='undefined'){
alert("undefined");
}
});
});
Or use by replace jQuery by $ sign. It will work.
you can try this way too......
$("document").ready(function(){
var txtuname;
$("#txtuname").keyup(function(){
if($("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if($("#txtuname").val().length>=6){
txtuname=$("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function(){
if(typeof txtuname=="undefined"){
alert("undefined");
}
else{
alert("defined");
}
});
});

Control+backspace in textbox javascript

I have a requirement of having a text-box with default value say "PF_". If I type something and press control+backspace All the values are been deleted. This problem occurs only If I have an underscore "_" at the end.
Javascript
var readOnlyLength = $('#field').val().length;
$('#output').text(readOnlyLength);
$('#field').on('keypress, keydown', function (event) {
var $field = $(this);
$('#output').text(event.which + '-' + this.selectionStart);
if ((event.which != 37 && (event.which != 39)) && ((this.selectionStart < readOnlyLength) || ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
return false;
}
});
Html
<input id="field" type="text" value="PF_" size="50" />
I have tried a sample fiddle.
Any Idea?
I'm not sure if this is what you're after, but this will reset the field to the previous value if the user tries to modify the read-only part:
$('#field').on('keypress, keydown', function (event) {
var $field = $(this);
var old = $field.val();
setTimeout(function(){
if($field.val().slice(0,3)!='PF_') {
$field.val(old);
}
},0);
});
Edit: in response to op's comments, try this code instead:
$('#field').on('keypress, keydown', function (event) {
var $field = $(this);
if(event.ctrlKey && event.which==8) { // ctrl-backspace
$field.val('PF_');
return false;
}
var old = $field.val();
setTimeout(function(){
if($field.val().slice(0,3)!='PF_') {
$field.val(old);
}
},0);
});
Fiddle
This is how I would do it:
$("#field").keyup(function(e){
if($(this).val().length < 3){
$(this).val("PF_");
}
});
Here is the JSFiddle demo

Javascript currency validation doesn't work if clamp button

I want to validate my input according following requirements:
value can be from 1.00 to 9999.99
value fractional part cannot have more than 2 digits
I have wrote following code:
html:
<input id="amount" maxlength="7" type="text" />
js:
$("#amount").on("keyup", function(){
var valid = /^[1-9]{1}\d{0,3}(\,\d{0,2})?$/.test(this.value),
val = this.value;
if(!valid){
console.log("Invalid input!");
this.value = val.substring(0, val.length - 1);
}
});
But if I clamps '0' it works bad.
Please help to fix.
JSFIDDLE
P.S.
If I press '0' for 3-4 seconds I see
expected result - all input input be clear
$("#amount").on("input", function(){
var valid = /^[1-9]{1}\d{0,3}(\.\d{0,2})?$/.test(this.value),
val = this.value;
if(!valid){
console.log("Invalid input!");
this.value = val.substring(0, val.length - 1);
}
});
http://jsfiddle.net/a2eqrquf/
My Regex isn't really on point, so someone might be able to tidy that up a bit more than I can. But that is working as it should.
This is what the number input was made for just use the following HTML:
<input id="money-input" type="number" value="1" min="1" max="9999.99" step="0.01">
If your want to restrict the number of decimals that can be entered you could simply add some JavaScript to round of the number:
(function() {
var input = document.getElementById('money-input');
input.addEventListener('blur', function() {
this.value = Math.round(this.value * 100) / 100;
});
})();
I have updated your regular expresion, so now it's working like you want.
Demo: http://jsfiddle.net/vY39r/391/
$("#amount").on("input", function(){
var valid = /^[0-9]{1}\d{0,3}(\.\d{0,2})?$/.test(this.value),
val = this.value;
if(!valid){
console.log("Invalid input!");
this.value = val.substring(0, val.length - 1);
}
});
hope it's helps.
$(".allownumericwithdecimal").live("keypress keyup ",function (event) {
var text = $(this).val();
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
if(text.indexOf('.') != -1 && event.which==190 )
{
if(text.match("^[0-9]+(\.[0-9]{0,2})?$")){
}
else{
$(this).val('') ;
}
}
if(text.indexOf('.') == -1 && text.length>7 && (event.which!=190 && event.which !=8 && event.which !=46 && event.which !=110 && event.which !=0)){
event.preventDefault();
}
});
$(".allownumericwithdecimal").live("blur",function (event){
var text = $(this).val();
if((text.indexOf('.') != -1)){
if((text.substring(text.indexOf('.'), text.indexOf('.').length).length)>2){
text = text.toString(); //If it's not already a String
text = text.slice(0, (text.indexOf("."))+3); //With 3 exposing the hundredths place
$(this).val(text);
}
}
});
this is what i use personally

Get default value of an input using jQuery

$(".box_yazi2").each(function () {
var default_value = this.value;
$(this).css('color', '#555'); // this could be in the style sheet instead
$(this).focus(function () {
if (this.value == default_value) {
this.value = '';
$(this).css('color', '#000');
}
});
$(this).blur(function () {
if (this.value == '') {
$(this).css('color', '#555');
this.value = default_value;
}
});
});
This function of default value of input doesnt work in FF, but perfectly works in IE
and ofcourse the input itself looks like this:
<input type="text" class="box_yazi2" id="konu" name="konu" value="Boş" />
Just use the defaultValue property:
var default_value = $(this).prop("defaultValue");
Or:
var default_value = this.defaultValue;
The solution is quite easy; you have an extra }); in your code (thanks # Box9).
I would encourage you to reuse the variable and not create dozens of jQuery objects.
I've changed your example to background-color but it will work.
$('.box_yazi2').each(function(index, element) {
var $element = $(element);
var defaultValue = $element.val();
$element.css('background-color', '#555555');
$element.focus(function() {
var actualValue = $element.val();
if (actualValue == defaultValue) {
$element.val('');
$element.css('background-color', '#3399FF');
}
});
$element.blur(function() {
var actualValue = $element.val();
if (!actualValue) {
$element.val(defaultValue);
$element.css('background-color', '#555555');
}
});
});
demo
$('input[type="text"]').focus( function(){
elementValue = $(this).val();
$(this).val("");
});
$('input[type="text"]').blur( function(){
if($(this).val() != elementValue && $(this).val() != ""){
}else{
$(this).val(elementValue);
}
});
I'm using the next code:
//clear the focused inputs
$('input[type="text"]').focus( function(){
if( $(this).attr('value') == $(this).attr('defaultValue') ){
$(this).attr('value', '');
};
} );
$('input[type="text"]').blur( function(){
if( $(this).attr('value') == '' ){
$(this).attr('value', $(this).attr('defaultValue') );
};
} );
Use this.defaultValue
Sorry for the link to w3notcools, http://www.w3schools.com/jsref/prop_text_defaultvalue.asp
You should use prop instead of so many functions to be honest, use 'delegate' instead of 'on' for late static binding.
$('.box_yazi2').each(function() {
$(this).on('focus', function(){
if($(this).val() == $(this).prop('defaultValue')){
$(this).val('');
$(this).css('color', '#000');
}
});
$(this).on('blur', function(){
if($(this).val() == ''){
$(this).val($(this).prop('defaultValue'));
$(this).css('color', '#000');
}
});
});

Same function for multiple jQuery objects

I want the same functions to run for 2 jQuery objects: $('input[type="text"]') and $('textarea[type=text]'). How can I combine those two in the code below? (currently, only input is included).
$('input[type="text"]').focus(function() {
if (this.value == this.defaultValue){
this.value = '';
}
if(this.value != this.defaultValue){
this.select();
}
});
$('input[type="text"]').blur(function() {
if ($.trim(this.value == '')){
this.value = (this.defaultValue ? this.defaultValue : '');
}
});
Thanks!
Try this:
$('textarea[type="text"], input[type="text"]').focus(...).blur(...);
Similarly you can also use jQuery's add function:
$('textarea[type="text"]').add('input[type="text"]').focus(...).blur(...);
May be easier to put a class on it and filter by that.
You could create a plugin:
jQuery.fn.clearDefValueOnFocus = function() {
return this.focus(function(){
if (this.value == this.defaultValue){
this.value = '';
}
if(this.value != this.defaultValue){
this.select();
}
}).blur(function(){
if (jQuery.trim(this.value) == ''){
this.value = this.defaultValue || '';
}
});
};
$('input[type="text"]').clearDefValueOnFocus();
$('textarea[type=text]').clearDefValueOnFocus();

Categories