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

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

<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">
1
2
3
delete
</div>​
Used a modified version of your code itself try

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

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.

Related

jQuery add/remove text from input string

I have a function that adds text into an input box. Basically you click a div and it activates the function by onclick="addvalue(“Name”)"
function addvalue(newdate){
var input = $("#datestobeexcluded");
input.val(input.val()+","+newdate);
};
But what I really need to do is to check the string inside the input value,
If it’s not there to add the text, which it does, and remove it if text is already present in string.
I am not doing well with jquery at the moment. Thank you in advance
var input = $("#datestobeexcluded");
if(input.val().search(newdate) >= 0)
{
input.val(input.val().replace(newdate,''));
}
else
{
input.val(input.val()+","+newdate);
}
And if you have multiple occurrences:
input.val(input.val().replace(/newdate/g,''));
You can use includes with RegExp:
var input = $("#datetobeexcluded");
input.val(input.val().includes(newdate) ? input.val().replace(new RegExp(newdate, "g"), "") : `${input.val()},${newdate}`);
You may replace your inline on click binding with jQuery styled click listener.
Then you may use the next code.
const $input = $('#your-input')
$('.extra-option').click(function() {
const inputString = $input.val()
const content = inputString ? inputString.split(',') : []
const stringToAdd = $(this).html()
const stringIndex = content.indexOf(stringToAdd)
if (stringIndex === -1) {
content.push(stringToAdd)
} else {
content.splice(stringIndex, 1)
}
$input.val(content.join(','))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="your-input" type="text" />
<div class="extra-option">Name</div>
<div class="extra-option">Company</div>
<div class="extra-option">Address</div>
At first, you need to figure out how you will provide clicked element value. Your approach is definitely wrong because you need to bind function on click, while you return undefined. For test purposes I use innerText.
At the second, you need to check if your string contains clicked div string or not. To simplify this logic, I use splitting by delimiter and then manage with an array of entries.
The last step, you need to update your input value.
I guess it's all.
Let me know if you have any question.

Changing a dynamically created label's text with keyup() issue

I am creating a form dynamically and therefore edit the form elements’ properties. When attempting to change the label, assigning an auto-generated id works fine but when changing this label using the generated id, the function or keyup() from jQuery keeps calling all the previously created label id(s). this means when i want to edit one label, it ends up editing every label.
HTML
<input type="text" id="change-label"><br><br>
<button id="add-button">add label</button>
<div id="add-label"></div>
JavaScript/jQuery
$('#add-button').click(function(){
var div = document.createElement('div');
var textLabel = document.createElement('label');
var labelNode = document.createTextNode('untitled');
textLabel.appendChild(labelNode);
textLabel.id = autoIdClosure();
$('#change-label').val('untitled');
div.appendChild(textLabel);
$('#add-label').append(div);
});
var autoIdClosure = (function(){
var counter = 0;
var labelId = "textInputLabel";
return function(){
counter += 1;
var id = labelId + counter;
editLabelWrapper(id)
return id;
}
})();
function editLabelWrapper(id){
function editLabel(){
var value = $(this).val();
$("#"+id).text(value);
}
$("#change-label").keyup(editLabel).keyup();
}
I’ve already found an alternative using onkeyup="$('#'+globaID).text($(this).val());", but I need to understand what I was doing wrong so I can learn from it.
JSFiddle
I think you are overthinking the matter...
Instead of using an unique id, rather use classes, makes it easier to handle.
So change <div id="add-label"></div> to <div class="add-label"></div>
Then what you want to do is, when a value is given in #change-label you want it in the last div.add-label.
So the function will become this:
$("#change-label").on('keyup', function() {
$('.add-label:last').text( $(this).val() );
});
Next what you want to do is bind a function to #add-button. Once it gets clicked, we want to add a new div.add-label after the last one. And empty the #change-label. You can do that by using this function:
$('#add-button').on('click', function() {
$('.add-label:last').after('<div class="add-label"></div>');
$('#change-label').val('');
});
Updated Fiddle

TextBox create div javascript

I want to create different "div" in the body when the user enter the number of div in the textbox
For example, with the markup for my textbox: <input type="text" id="numberDiv" maxlength="1">
I am using the following JS:
<script>
$(document).ready(
function () {
$('#numberDiv').keyup(
function () {
var s = $("#numberDiv").val();
var nbrDiv = parseInt(s);
for(var i = 0; i <= nbrDiv; i++)
{
var iDiv = document.createElement('div');
iDiv.id = 'div';
document.getElementsByTagName('body')[0].appendChild(iDiv);
iDiv.innerHTML = "I'm a div";
}
})
});
</script>
My problem is when I put for example "1" in the textbox it creates 1 div but when I press an other key (for example: enter, alt, ...) it creates another div even if my input has the maxlength="1". How can I disable the pressing on another key when my first number is in the textbox.
First of all, you shouldn't use the same id for all of the divs. So instead of iDiv.id = 'div' you might want to do this:
iDiv.attr('id', 'div[' + i + ']');
I'm not sure about your requirements, but you might also want to check the number of divs before creating new ones:
$('#numberDiv').keyup(function() {
var s = $(this).val();
var currentDivsCount = $('body > div').length;
var nbrDiv = parseInt(s, 10) - currentDivsCount;
if (isNaN(nbrDiv)) return;
var iDiv;
for (var i = 0; i < Math.abs(nbrDiv); i++) {
if (nbrDiv > 0) {
iDiv = $('<div>I\'m a div</div>');
iDiv.attr('id', 'div[' + (currentDivsCount + i) + ']');
iDiv.appendTo('body');
} else {
$('body > div:last').remove();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="numberDiv" maxlength="1">
you can mask your input like so:
first Import the jQuery mask library,
Textbox : <input type="text" id="numberDiv" maxlength="1">
$(document).ready(
function () {
$('#numberDiv').mask('0');
});
this will only allow 1 number (digit character) to be in the box at a time
look here for more examples
and here to download the mask plugin
either you put the check on keycode for using event, if it is for numeric value then only run the logic. simple if in function will work.
<script>
$( "#whichkey" ).on( "keydown", function( event ) {
if( event.which < // range for 1 to 9){
//logic comes here
}
});
</script>
or you can add code to remove innerhtml before adding the div. So even if user press anyother key like enter. It will delete the innerhtml and then add the 1 div.

jquery toggle depending on value of textbox

This must be very simple, but I just got stuck with this... I have a list of products with an input field for the quantity and next to it a column with the prices. The prices are displaying two values. One of them is hidden. If the value of the input field goes over a certain value, it should hide the other price.
Example:
(input: [], show price1price2 )
input: [2], show <span class=one>price1</span>
input: [5], show <span class=one>price1</span>
input: [8], show <span class=two>price2</span>
input: [9], show <span class=two>price2</span>
My code so far (example, since I show just 2 products):
<form name="formname" action="formaction" method="post">
prod 1<input type="text" value="" class="class1" size="3"><span class="one">$1.00</span><span class="two">$2.00</span>
prod 2<input type="text" value="" class="class1" size="3"><span class="one">$4.00</span><span class="two">$6.00</span>
</form>
And at the bottom in script tags:
$(document).ready(function() {
if($('input.class1').val() > 5) {
$('.one').show();
$('.two').hide();
}
});
What am I missing? The form name perhaps?
This is just the first part...
My other question would be.. how can I make it so that if the sum of all the input fields (with class1 as class) is more than 5, do the same. (So now depending on the sum of the input fields, rather than each individual one)
var inputs = $('input[class^=class]'); // get inputs which class name
// start with "class" eg: class1, class2..
// fire blur event
// you may use keyup or something else
inputs.on('blur', function(e) {
var val = 0;
// adding all inputs value
// of all inputs with class = blured input class
$('input.' + this.className).each(function() {
val += parseInt( this.value, 10);
});
// checking for condition
if (val > 5) {
$(this).next('.one').show().next('.two').hide();
} else {
$(this).next('.one').hide().next('.two').show();
}
});
Demo with blur
Demo with keyup
Note
Place you all jQuery codes within $(document).ready().
According to comment
See this update
Code
if (val > 5) {
$('.one').show();
$('.two').hide();
} else {
$('.one').hide();
$('.two').show();
}
Update after last comment
Just change
val += parseInt( this.value, 10);
to
val += parseInt( this.value || 0, 10); // default 0, if no value given
According to comment
How to implement above code for select box?
var selects = $('select[class^=class]'); // get selects which class name
// start with "class" eg: class1, class2..
// fire change event
selects.on('change', function(e) {
var val = 0;
// adding all selects value
$('select.' + this.className).each(function() {
val += parseInt( this.value, 10);
});
// checking for condition
if (val > 5) {
$(this).next('.one').show().next('.two').hide();
} else {
$(this).next('.one').hide().next('.two').show();
}
});
You are calling this on page load, you need to run it each time the value of the input fields is changed.
Consider wrapping your if block in this:
$('input.class1').blur(function() {
if($('input.class1').val() > 5) {
$('.one').show();
$('.two').hide();
}
});
Or something to that effect, consider using $.on().
If you want to sum them, assign each input a common class, and use $.each():
$('.common-class').each(function() {
sum = sum + $(this).val()
});
Hope this helps.

changing input text to textarea just like in facebook

i would like to replicate that you see a regular input text and when you click it changes into textarea.
is this a hidden layer or is it actually changing the input to textarea? how to do it?
I do believe it's always a textarea and on focus they just change the height of the textarea.
Edit: yes, it is. They use scripting to do everything with a textarea, there is no input field.
<textarea onfocus='CSS.addClass("c4b900e3aebfdd6a671453", "UIComposer_STATE_INPUT_FOCUSED");CSS.removeClass("c4b900e3aebfdd6a671453_buttons", "hidden_elem");window.UIComposer && UIComposer.focusInstance("c4b900e3aebfdd6a671453");' id="c4b900e3aebfdd6a671453_input" class="UIComposer_TextArea DOMControl_placeholder" name="status" title="What's on your mind?" placeholder="What's on your mind?">
What's on your mind?
</textarea>
One method that I found was to have a text area that begins with a smaller width and height and then to dynamically resize it.
function sz(t) {
a = t.value.split('\n');
b=1;
for (x=0;x < a.length; x++) {
if (a[x].length >= t.cols) b+= Math.floor(a[x].length/t.cols);
}
b+= a.length;
if (b > t.rows) t.rows = b;
}
then you would call your function with an onclick event
onclick="function sz(this)"
I found this here
Fellgall Javascript
One problem that he does mention is that this only functions on browsers that support it.
You can combine the jQuery widget you can find here with some coding
Example:
<div id="myform">
<form>
<textarea></textarea>
<button type="submit" style="display:none;">Post</button>
</form>
</div>
<script>
$(document).ready(function(){
var widget = $('#myform textarea');
var button = $('#myform button');
var tarea = widget[0];
// turn the textarea into an expandable one
widget.expandingTextArea();
var nullArea = true;
tarea.value = "What's on your mind?";
widget.focus(function() {
button.css('display', 'block');
if (nullArea) {
tarea.value = "";
nullArea = false;
}
});
widget.blur(function() {
if ($.trim(tarea.value) == "") {
tarea.value = "What's on your mind?";
button.css('display', 'none');
nullArea = true;
}
});
});
</script>
This code will hide by default the post button and will show it only when the textarea is focused or when you already have written something into it (you may want to hide/show a div instead or anything you want).
If jQuery is an option for you at all, there's a jQuery plugin that does just this called Jeditable.
Check out the demos here.
One way to do this is to code a dynamic textarea. This article explains how to do it: http://www.felgall.com/jstip45.htm
Another way to do it is to change the type of the object. Let's say you place your input text in a div tag (its ID being "commentBox". The code would then be:
//when you click on the textbox
function makeTextArea()
{
document.forms[0].getElementById("commentBox").innerHTML = "<textarea id=\"comments\" onBlur=\"backToTextBox()\"></textarea>";
document.forms[0].getElementById("comments").focus();
}
//when you click outside of the textarea
function backToTextBox()
{
document.forms[0].getElementById("commentBox").innerHTML = "<input type=\"text\" id=\"comments\" onFocus=\"makeTextArea()\"/>";
}

Categories

Resources