Delete last character from input

How could I delete the last character from an input in JQuery? For example, onclick of something, it deletes the last character (a comma in my case) from an input field.

$(input).val(
    function(index, value){
        return value.substr(0, value.length - 1);
})

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));

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.

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*$/

$(document).on('click', '.backspace', function(){
    let value = $('#output').val();
    console.log(value);
    v = value.slice(0,-1);
    let v = value.slice(0,-1);
    console.log(v);
    $('#output').value(value);
});

function back_space() {

       var arrayexit = document.getElementById("tbtwo").value;

       for (var i = 0; i < arrayexit.length; i++) 
        {
            var output = arrayexit.slice(0, -1);
            document.getElementById("tbtwo").value = output;

        }


    }

Html code


<input oninput="remove(this.value)" type="text" id="mytext" />

Js code

function remove(val) {
    document.querySelector("#mytext").value = val.slice(0, -1);
}


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   JavaScript multithreading

Similar Posts