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
Asked
Active
Viewed 1.6k times
5
-
5what have you tried? can you post an simple example of the page on jsfiddle.net? – nathan gonzalez Aug 29 '12 at 21:13
-
do you mean a new character is attached at the end of your sting on each button click? – arjuncc Aug 29 '12 at 21:19
-
referthis from the stack-overflow itself. You have a good example too. [1]: http://stackoverflow.com/questions/952924/javascript-chop-slice-trim-off-last-character-in-string – arjuncc Aug 29 '12 at 21:23
-
so this is basically what I am doing so far.. http://jsfiddle.net/jeni/jfs4x/ – jeni Aug 29 '12 at 21:34
-
Thanks for all the replies, I'm sure they all worked great but arjuncc made it really simple! – jeni Aug 30 '12 at 00:40
-
you need to be lucky to get the "give me that code" – dejjub-AIS Nov 17 '12 at 07:09
-
@NoobASThreeDeveloper - huh? – jeni Mar 02 '13 at 03:11
3 Answers
9
<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

arjuncc
- 3,227
- 5
- 42
- 77
3
the simple answer is, if you are using jquery, to do something like this:
//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));
});

nathan gonzalez
- 11,817
- 4
- 41
- 57
-
If I try to use this, the console says `TypeError: textVal.length is not a function` – Cody Guldner Mar 20 '13 at 01:16
-
@CodyGuldner, yeah, that must've been a typo. length is a property. – nathan gonzalez Mar 20 '13 at 03:27
-
0
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.

austincheney
- 1,189
- 9
- 11