I'm trying to put a comma on a textbox that should only accept numbers. What I did is instead of using type="numbers", I limited the textbox to only accept number keyCodes.
$('#salary').keydown(function (e) {
var keyCode = e.which;
if (keyCode != 8 && keyCode != 9 && keyCode != 13 && keyCode != 37 && keyCode != 38 && keyCode != 39 && keyCode != 40 && keyCode != 46 && keyCode != 110 && keyCode != 190) {
if (keyCode < 48) {
e.preventDefault();
} else if (keyCode > 57 && keyCode < 96) {
e.preventDefault();
} else if (keyCode > 105) {
e.preventDefault();
}
}
});
What I want is that after the input is edited(out of focus), the textbox automatically shows commas similar to this value:
1,000,000.00
I am clueless on what to do or use to add comma's on the textbox.
$( "#salary" ).blur(function() {
$( "#salary" ).val( parseFloat($( "#salary" ).val(), 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());
});
Try this solution for add comma in numbers
$('#salary').keydown(function (){
var x = $('#salary').val();
$('#salary').val(addCommas(x));
function addCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
});
Could you please try with script below. Comma will be remove on click on textbox and thousand seperator will be added after focus out
$( "#salary" ).click(function() {
$( "#salary" ).val( $("#salary").val().replace(/,/g, ''));
});
$( "#salary" ).blur(function() {
$( "#salary" ).val( addCommas($( "#salary" ).val());
});
function addCommas(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
for minus and integer only
$("#amount").keypress(function (e) {
var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^\-/0-9]/);
if (verified) {
e.preventDefault();
}
});
for integer only
$("#amount").keypress(function (e) {
var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
if (verified) {
e.preventDefault();
}
});
not to display the comma when focus in
$("#amount").focus(function () {
var str = $(this).val();
$(this).val(str.replace(/,/g,''));
});
to display the comma when focus out
$("#amount").focusout(function () {
if ($(this).val().search(",") > 0){
return false;
} else {
if ($(this).val()) {
var add_comma = new Intl.NumberFormat().format($(this).val());
$(this).val(add_comma);}}
});
after press key "," i append new input, when i use backspace last input is removed, but after delete all inputs when i press again "," code return all inputs, not one. how fix it?
http://jsfiddle.net/3r79hyoL/
$(".multipleField").keyup(function(e) {
var key = e.which ? e.which : event.keyCode;
if (key == 110 || key == 188) {
e.preventDefault();
var value = $(this).val();
$(this).val(value.replace(",", ""));
$(this).first().clone().appendTo(".multipleFields").focus().val("");
event.preventDefault();
$(this).addClass('makeBorder');
replaceAndCopy();
}
if (key == 8) {
e.preventDefault();
if ($(".multipleFields").last().val() == "" && $(".multipleField").length > 1) {
$(".multipleField").last().remove();
$(".multipleField").last().focus();
}
}
});
function replaceAndCopy() {
$(".multipleField").keyup(function(e) {
var key = e.which ? e.which : event.keyCode;
if (key == 110 || key == 188) {
e.preventDefault();
var value = $(this).val();
$(this).val(value.replace(",", ""));
$(this).clone().appendTo(".multipleFields").focus().val("");
$(this).addClass('makeBorder');
replaceAndCopy();
}
if (key == 8) {
if ($(".multipleFields").last().val() == "" &&
$(".multipleField").length != 1) {
$(".multipleField:last").remove();
e.preventDefault();
$(".multipleField").last().focus();
}
}
});
}
The problem is that you are attaching new event listeners to every input. So when you go back to an input that is not the last one the event is fired more than one time.
function replaceAndCopy() {
// Add new event listener to all inputs, instead of the last
// $(".multipleField").keyup(function(e) {
// Change to
$(".multipleField").last().keyup(function(e) {
var key = e.which ? e.which : event.keyCode;
if (key == 110 || key == 188) {
e.preventDefault();
var value = $(this).val();
$(this).val(value.replace(",", ""));
$(this).clone().appendTo(".multipleFields").focus().val("");
$(this).addClass('makeBorder');
replaceAndCopy();
}
if (key == 8) {
if ($(".multipleFields").last().val() == "" && $(".multipleField").length != 1) {
$(".multipleField:last").remove();
e.preventDefault();
$(".multipleField").last().focus();
}
}
});
I would say I am fairly decent with javascript and jQuery, well, enough to get the job done and done pretty well.
I do however lack a deep understanding of js.
I have created some functions for highlighting table elements.
ctrl+click toggles selections
shift+click+drag highlights selection
My question does not pertain to whether or not my implementation is the best way or not but ...
How do I abstract this functionality so I can add this functionality to any table. Like if I add more highlighting features and such and put this in its own .js file. How would I attach it to any html table?
Sorry if this has already been answered, but I could not think of what to search for.
Thank you.
****Newest Code****
This code is in its own .js file and is attached to my table.
All the current functionality is there. The only thing I am weary of is the .off() functions. In my case, I am reloading new tables.... as I type this, I realize I should just empty the tr's from the table instead of recreating a new table all the time, then I could get rid of the .off() calls.
$.fn.addEvents = function(obj)
{
console.log("Adding events to table");
var properties = $.extend(true,
{
shifting: false,
ctrling: false,
mousing: false,
mouseenter: 0,
mouseleave: 0,
mousestartindex: 0,
mouseenterindex: 0,
mouseleaveindex: 0,
trajectory: null,
tmptrajectory: null
}, obj || {});
$(document)
.off('mouseup')
.on('mouseup', function(e)
{
properties.mousing = false;
properties.trajectory = null;
})
.off("keyup")
.on("keyup", function(e)
{
if(e.which == 16)
{
properties.shifting = false;
}
if(e.which == 17)
{
properties.ctrling = false;
}
})
.off("keydown")
.on("keydown", function(e)
{
if(e.which == 16)
{
properties.shifting = true;
}
if(e.which == 17)
{
properties.ctrling = true;
}
if($(this).find('tr.selected').length > 0)
{
switch(e.which)
{
//case 37: // left
//break;
case 38: // up
var index = $(this).find('tr.selected').index();
if(index > 0)
{
$(this).find('tr').removeClass('selected');
$(this).find('tr td').removeClass('selected');
$(this).find('tr:eq(' + index + ')').addClass('selected');
$(this).find('tr:eq(' + index + ') td').addClass('selected');
}
break;
//case 39: // right
//break;
case 40: // down
var index = $(this).find('tr.selected').index();
if(index < $(this).find('tr').length - 2)
{
$(this).find('tr').removeClass('selected');
$(this).find('tr td').removeClass('selected');
$(this).find('tr:eq(' + (index+2) + ')').addClass('selected');
$(this).find('tr:eq(' + (index+2) + ') td').addClass('selected');
}
break;
case 117: // f6
var index = $(this).find('tr.selected').index();
if(index > 0)
{
....
}
break;
case 118: // f7
var index = $(this).find('tr.selected').index();
if(index < $(this).find('tr').length - 1)
{
....
}
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
}
return;
});
return $(this)
.off('click')
.off('contextmenu')
.on('click', function()
{
if(!properties.ctrling && !properties.shifting)
{
$('#datatablebody tr, #datatablebody tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
else if(properties.ctrling && $(this).hasClass('selected'))
{
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
else if(properties.ctrling && !$(this).hasClass('selected'))
{
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
})
.on('contextmenu', function(ev)
{
ev.preventDefault();
$('#datatablebody tr, #datatablebody tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
showContextMenuTR($(this).closest('tr').attr('id'), ev.clientX, ev.clientY);
return false;
})
.off('mousedown')
.on('mousedown', function(e)
{
properties.mousing = true;
properties.mousestartindex = $(this).index();
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
})
.off('mouseenter')
.on('mouseenter', function(e)
{
properties.mouseenter = e.clientY;
properties.mouseenterindex = $(this).index();
if(properties.tmptrajectory === properties.trajectory)
{
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
}
})
.off('mouseleave')
.on('mouseleave', function(e)
{
properties.mouseleave = e.clientY;
if(properties.shifting && properties.mousing)
{
properties.tmptrajectory = properties.mouseenter - properties.mouseleave < 0?1:-1;
}
if(properties.trajectory != null && properties.tmptrajectory !== properties.trajectory && $(this).index() !== properties.mousestartindex)
{
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
}
if(properties.shifting && properties.mousing)
{
if(properties.trajectory == null)
{
properties.trajectory = properties.tmptrajectory;
}
else if(properties.tmptrajectory !== properties.trajectory && $(this).index() === properties.mousestartindex)
{
properties.trajectory = properties.tmptrajectory;
}
}
})
.off('mouseup')
.on('mouseup', function(e)
{
properties.mousing = false;
properties.trajectory = null;
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
});
}
function multiselectrow(obj)
{
if($(obj).hasClass('selected'))
{
$(obj).removeClass('selected');
$(obj).find('td').removeClass('selected');
}
else
{
$(obj).addClass('selected');
$(obj).find('td').addClass('selected');
}
}
you can wrap all this in a function since you have some local variables related to individual selection
$.fn.addEvents = function(obj) {
var properties = $.extend(true, {
shifting: false,
ctrling: false,
mousing: false,
mouseenter: 0,
mouseleave: 0,
trajectory: null
}, obj || {});
return $(this)
.off('click')
.off('contextmenu')
.on('click', function() {
.....
})
.on('mouseleave', function(e) {
//rename your local variables with `properties.` prefix
properties.mouseleave = e.clientY;
if (properties.shifting && properties.mousing) {
tmptrajectory = properties.mouseenter - properties.mouseleave < 0 ? 1 : -1;
}
if ($(this).hasClass('selected') && properties.shifting && properties.mousing && properties.trajectory != null && properties.trajectory != tmptrajectory) {
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
....
});
}
usage
$('#datatablebody tr').addEvents({ shifting: false, ctrling: true }); //custom settings
$('#someother tr').addEvents(); //default settings
you could add that functionality to a class and add that class to the tables you want to affect...
Here I create the class .myTableBeh and all tables with that class will have the behaviour you programmed.
var shifting = false;
var ctrling = false;
var mousing = false;
var mouseenter = 0;
var mouseleave = 0;
var trajectory = null;
$('.myTableBeh tr')
.off('click')
.off('contextmenu')
.on('click', function()
{
if(!ctrling)
{
$('.myTableBeh tr, .myTableBeh tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
else if(ctrling && $(this).hasClass('selected'))
{
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
else if(ctrling && !$(this).hasClass('selected'))
{
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
})
.on('contextmenu', function(ev)
{
ev.preventDefault();
$('.myTableBeh tr, .myTableBeh tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
showContextMenuTR($(this).closest('tr').attr('id'), ev.clientX, ev.clientY);
return false;
})
.off('mousedown')
.on('mousedown', function(e)
{
mousing = true;
multiselectrow($(this));
})
.off('mouseenter')
.on('mouseenter', function(e)
{
mouseenter = e.clientY;
multiselectrow($(this));
})
.off('mouseleave')
.on('mouseleave', function(e)
{
mouseleave = e.clientY;
if(shifting && mousing)
{
tmptrajectory = mouseenter - mouseleave < 0?1:-1;
}
if($(this).hasClass('selected') && shifting && mousing && trajectory != null && trajectory != tmptrajectory)
{
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
if(shifting && mousing && trajectory == null)
{
trajectory = tmptrajectory;
}
})
.off('mouseup')
.on('mouseup', function(e)
{
mousing = false;
trajectory = null;
multiselectrow($(this));
});
Thanks to the answer from #JAG I was able to create a nice add on to any HTML table that handles highlighting.
Check out the fiddle for the working version and please use it if you find it helpful or useful for your site.
You can even implement keys to move the tr position up or down in the table. I removed my implementation because it was specific to the project I am working on.
I made it so you have to mouse over the table in order to interact with it and mouse leave to un-focus it.
https://jsfiddle.net/kwj74kg0/2/
//Add the events simply by running this
$('#dtable tr').addEvents(0);
/**
* This add on can be applied and customized to any html tr set i.e. $('#tableid tr').addEvents()
* It will add highlighting capability to the table.
*
* Single click highlight tr
* Click -> Shift + click highlight/toggle range
* Shift+MouseDown+Drag highlight/toggle range
* Ctrl+Click toggle item
*
*
* #author Michaela Ervin
*
* #param tabindex
*
* Help from JAG on http://stackoverflow.com/questions/39022116/create-a-javascript-object
*/
$.fn.addEvents = function(tabindex)
{
console.log("Adding events to table");
var properties = $.extend(true,
{
shifting: false,
ctrling: false,
mousing: false,
mouseenter: 0,
mouseleave: 0,
mousestartindex: 0,
mouseenterindex: null,
mouseleaveindex: null,
trajectory: null,
tmptrajectory: null
}, {});
/**
* Add events to closest table.
*/
$(this)
.closest('table')
.attr('tabindex', tabindex)
.off('mouseenter')
.on('mouseenter', function()
{
$(this).focus();
})
.off('mouseleave')
.on('mouseleave', function()
{
$(this).blur();
properties.mousing = false;
properties.trajectory = null;
properties.mouseenterindex = null;
properties.mouseleaveindex = null;
properties.mouseintermediateindex = null;
})
.off("keyup")
.on("keyup", function(e)
{
if(e.which == 16)
{
properties.shifting = false;
}
if(e.which == 17)
{
properties.ctrling = false;
}
})
.off("keydown")
.on("keydown", function(e)
{
if(e.which == 16)
{
properties.shifting = true;
}
if(e.which == 17)
{
properties.ctrling = true;
}
if($(this).find('tr.selected').length > 0)
{
switch(e.which)
{
//case 37: // left
//break;
case 38: // up
var index = $(this).find('tr.selected').index();
if(index > 0)
{
$(this).find('tr').removeClass('selected');
$(this).find('tr td').removeClass('selected');
$(this).find('tr:eq(' + index + ')').addClass('selected');
$(this).find('tr:eq(' + index + ') td').addClass('selected');
}
break;
//case 39: // right
//break;
case 40: // down
var index = $(this).find('tr.selected').index();
if(index < $(this).find('tr').length - 2)
{
$(this).find('tr').removeClass('selected');
$(this).find('tr td').removeClass('selected');
$(this).find('tr:eq(' + (index+2) + ')').addClass('selected');
$(this).find('tr:eq(' + (index+2) + ') td').addClass('selected');
}
break;
case 117: // f6
var index = $(this).find('tr.selected').index();
if(index > 0)
{
//Function to move tr 'up'.
}
break;
case 118: // f7
var index = $(this).find('tr.selected').index();
if(index < $(this).find('tr').length - 1)
{
//Function to move tr 'down'.
}
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
}
return;
});
/**
* Add tr specific events
*/
return $(this)
.off('click')
.on('click', function()
{
if(!properties.shifting && properties.mouseenterindex != null)
{
properties.mouseenterindex = null;
properties.mousing = false;
}
if(!properties.ctrling && !properties.shifting && properties.mouseenterindex == null)
{
$(this).parent().find('tr').removeClass('selected');
$(this).parent().find('tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
else if(properties.ctrling && $(this).hasClass('selected'))
{
$(this).removeClass('selected');
$(this).find('td').removeClass('selected');
}
else if(properties.ctrling && !$(this).hasClass('selected'))
{
$(this).addClass('selected');
$(this).find('td').addClass('selected');
}
if(properties.mouseenterindex == null)
{
properties.mouseenterindex = $(this).index();
}
else if(properties.shifting && properties.mouseenterindex != null)
{
properties.mouseleaveindex = $(this).index();
highlightRange($(this).parent(), properties.mouseenterindex, properties.mouseleaveindex, properties.mouseenterindex);
properties.mouseenterindex = null;
properties.mouseleaveindex = null;
}
})
.off('contextmenu')
.on('contextmenu', function(ev)
{
ev.preventDefault();
$(this).parent().find('tr').removeClass('selected');
$(this).parent().find('tr td').removeClass('selected');
$(this).addClass('selected');
$(this).find('td').addClass('selected');
//Put your context menu here
return false;
})
.off('mousedown')
.on('mousedown', function(e)
{
properties.mousing = true;
properties.mousestartindex = $(this).index();
if(properties.shifting && properties.mousing && properties.mouseenterindex == null)
{
multiselectrow($(this));
}
})
.off('mouseenter')
.on('mouseenter', function(e)
{
properties.mouseenter = e.clientY;
if(properties.tmptrajectory === properties.trajectory)
{
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
}
})
.off('mouseleave')
.on('mouseleave', function(e)
{
properties.mouseleave = e.clientY;
if(properties.shifting && properties.mousing)
{
properties.tmptrajectory = properties.mouseenter - properties.mouseleave < 0?1:-1;
}
if(properties.trajectory != null && properties.tmptrajectory !== properties.trajectory && $(this).index() !== properties.mousestartindex)
{
if(properties.shifting && properties.mousing)
{
multiselectrow($(this));
}
}
if(properties.shifting && properties.mousing)
{
if(properties.trajectory == null)
{
properties.trajectory = properties.tmptrajectory;
}
else if(properties.tmptrajectory !== properties.trajectory && $(this).index() === properties.mousestartindex)
{
properties.trajectory = properties.tmptrajectory;
}
}
})
.off('mouseup')
.on('mouseup', function(e)
{
properties.mousing = false;
properties.trajectory = null;
if(!properties.shifting)
{
properties.mouseenterindex = null;
properties.mouseleaveindex = null;
}
});
}
function multiselectrow(obj)
{
if($(obj).hasClass('selected'))
{
$(obj).removeClass('selected');
$(obj).find('td').removeClass('selected');
}
else
{
$(obj).addClass('selected');
$(obj).find('td').addClass('selected');
}
}
function highlightRange(obj, start, end, mouseenterindex)
{
if(start < end)
{
for(var i=start; i<=end; i+=1)
{
if(i !== mouseenterindex)
{
multiselectrow($(obj).find('tr').eq(i));
}
}
}
else
{
for(var i=start; i>=end; i-=1)
{
if(i !== mouseenterindex)
{
multiselectrow($(obj).find('tr').eq(i));
}
}
}
}
I want to make something where when you are in a input you can press a button and it will fill it with a character(depending on the button) and move onto the next input.
$('.today').keyup(function(e) {
if ($.inArray(e.keyCode, [69, 88, 191]) === -1) { // e, x, / respectively
e.preventDefault(); // don't print the character
return false;
}
var self = $(this);
var currentInput = self.data('number');
var next = $(currentInput + 1);
var previous = $(currentInput - 1);
var keyCode = e.keyCode || e.which;
var num = self.data('number') + 1;
var nom = self.data('number') - 1;
if(('input.today[data-number="' + num +'"]').length && keyCode === 40)
$('input.today[data-number="' + num +'"]').focus()
else if(('input.today[data-number="' + nom +'"]').length && keyCode === 38)
$('input.today[data-number="' + nom +'"]').focus();
else if(('input.today[data-number="' + num +'"]').length && self.val().length == self.attr('size')) {
$('input.today[data-number="' + num +'"]').focus();
}
});
$('.today').keyup(function(e) {
if ($.inArray(e.keyCode, [69, 88, 191]) === -1) {
$( this ).next().focus();
}else{
return false;
}
});
My JavaScript code is as follows:
$(document).keydown(function(event){
var move, inter;
clearInterval(inter);
inter = setInterval(move = function() {
var dir = $(".snake").data('dir');
var snake = $('.snake');
var food = $('.food');
if(dir == 'top') {
snake.css({"top": $(".snake").position().top + 5 + "px"});
}
if(dir == 'bottom') {
snake.css({"top": $(".snake").position().top - 5 + "px"});
}
if(dir == 'left') {
snake.css({"left": $(".snake").position().left + 5 + "px"});
}
if(dir == 'right') {
snake.css({"left": $(".snake").position().left - 5 + "px"});
}
}, 1500);
if(event.which == 40) {
$(".snake").data('dir','top');
} else if(event.which == 39) {
$(".snake").data('dir','left');
} else if(event.which == 37) {
$(".snake").data('dir','right');
} else if(event.which == 38) {
$(".snake").data('dir','bottom');
};
});
http://jsfiddle.net/6bKHc/94/
When I hold down one of the arrows keys, the snake is starting to move faster, how can I turn that off? You can test it yourself.
Your setInterval is called inside your eventhandler. Move setinterval outside, along with a shared dir variable. Then you will have no need for clearinterval.
var dir = 'bottom';
setInterval(move = function() {
var snake = $('.snake');
var food = $('.food');
if(dir == 'top') {
snake.css({"top": $(".snake").position().top + 5 + "px"});
}
if(dir == 'bottom') {
snake.css({"top": $(".snake").position().top - 5 + "px"});
}
if(dir == 'left') {
snake.css({"left": $(".snake").position().left + 5 + "px"});
}
if(dir == 'right') {
snake.css({"left": $(".snake").position().left - 5 + "px"});
}
}, 150);
$(document).keydown(function(event){
if(event.which == 40) {
dir = 'top';
} else if(event.which == 39) {
dir = 'left';
} else if(event.which == 37) {
dir = 'right';
} else if(event.which == 38) {
dir = 'bottom';
};
});
http://jsfiddle.net/zatsq/