javascript 单击时如何从输入字段中删除最后一个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12186603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:31:57  来源:igfitidea点击:

How do I remove last character from input field on click?

javascript

提问by jeni

I have a form that when buttons are clicked, it enters a value into an input field. I want to add another button that deletes the last character added. How would I accomplish this using jQuery

我有一个表单,当单击按钮时,它会在输入字段中输入一个值。我想添加另一个按钮来删除添加的最后一个字符。我将如何使用 jQuery 完成此操作

回答by arjuncc

<script>
function addTextTag(txt)
{
document.getElementById("text_tag_input").value+=txt;
}
function removeTextTag()
{
var strng=document.getElementById("text_tag_input").value;
document.getElementById("text_tag_input").value=strng.substring(0,strng.length-1)
}
</script>

<input id="text_tag_input" type="text" name="tags" />

    <div class="tags_select">
    <a href="javascript:addTextTag('1')">1</a>
    <a href="javascript:addTextTag('2')">2</a>
    <a href="javascript:addTextTag('3')">3</a>
    <a href="javascript:removeTextTag()">delete</a>
</div>?

Used a modified version of your code itself try

使用您的代码本身的修改版本尝试

回答by nathan gonzalez

the simple answer is, if you are using jquery, to do something like this:

简单的答案是,如果您使用 jquery,请执行以下操作:

//select the button, add a click event
$('#myButtonId').on('click',function () { 
    //get the input's value
    var textVal = $('#myInputId').val();
    //set the input's value
    $('#myInputId').val(textVal.substring(0,textVal.length - 1));
});

回答by austincheney

var lastChar = function (x) {
        "use strict";
        var a = document.getElementById(x),
            b = a.value;
        a.value = b.substring(0, b.length - 1);
    };

No jQuery required. The x variable is the id of the input you want to mutilate.

不需要jQuery。x 变量是您要删除的输入的 ID。