Delete last character from input
The following works, albeit it's perhaps a little clunky:
$('#idOfButtonToClick').click(
function(){
var inputString = $('#idOfInput').val();
var shortenedString = inputString.substr(0,(inputString.length -1));
$('#idOfInput').val(shortenedString);
});
JS Fiddle demo.
Revised demo, that checks for the last character being a ,
character before truncating the string:
$('#idOfButtonToClick').click(
function(){
var inputString = $('#idOfInput').val();
if (inputString.charAt(inputString.length - 1) == ',') {
var shortenedString = inputString.substr(0,(inputString.length -1));
$('#idOfInput').val(shortenedString);
}
return false;
});
JS Fiddle demo.
If you want to chop of any last character (not just comma, space), you can use slice
:
var $myInput = $('#myInput');
$myInput.val($myInput.val().slice(0, -1));
You can combine it with $.trim()
to remove extra spaces:
$myInput.val($.trim($myInput.val()).slice(0, -1));
$(input).val(
function(index, value){
return value.substr(0, value.length - 1);
})
These two lines will remove a trailing comma from a particular input. I'll leave it up to you to decide when it needs to be run (on change/on button click, etc).
var $theInput = $('#myInput');
$theInput.val($theInput.val().replace(/,$/, ''));
If you also want to get rid of any possible whitespace at the end, change the regex to this:
/\s*,\s*$/