sir_thursday
sir_thursday

Reputation: 5409

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.

Upvotes: 25

Views: 69838

Answers (7)

The News
The News

Reputation: 11

$(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);
});

Upvotes: 1

Html code


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

Js code

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

Upvotes: 1

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;

        }


    }

Upvotes: 0

RiaD
RiaD

Reputation: 47619

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

Upvotes: 48

Mrchief
Mrchief

Reputation: 76198

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

Upvotes: 11

David Thomas
David Thomas

Reputation: 253308

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.

Upvotes: 6

nickf
nickf

Reputation: 545985

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

Upvotes: 4

Related Questions