Autoresize textarea remove rows on backspace - javascript

I have the following code for autoresizing a textarea:
HTML:
<textarea class="autoresize" id="txt" rows="2"></textarea>
JS:
$('#txt').keydown(function(e) {
var $this = $(this),
rows = parseInt($this.attr('rows'));
// on enter, add a row
if (e.which === 13)
$this.attr('rows', rows + 1);
// on backspace, remove a row -- THIS IS THE PROBLEM
if (e.which === 8 && rows !== 2)
$this.attr('rows', rows - 1);
});
It works well, but when I hit backspace to erase a letter from a word, it also removes rows, and that's my problem.
I want it to shrink back when the user "deletes" empty rows but I don't know how to achieve it.
If you want, you can check it out in this fiddle.

You need to check if the last line is empty. Demo.
if (e.which === 8 && rows !== 2) {
lines = $(this).val().split('\n');
if(!lines[lines.length - 1]) {
$this.attr('rows', rows - 1);
}
}

Just count the length of the text you've entered (in every keydown) and then when you use backspace check if the last character (get it using the index from the length) is \n, only then delete row.

Related

next button not highlighting or displaying matches

The jquery highlight that I have created works well, but for some reason when I type something in the input field and hit the next button it doesn't highlight the terms. It only displays "1 of 0 mathches". I'm not sure why it won't highlight it.
Below is my script:
<script>
$("[data-search=next]").click(function() {
if (variableCounter < totalCount) variableCounter = variableCounter + 1;
else variableCounter = 1;
$(".kwt-count").html(variableCounter + " of " + totalCount + " Matches");
});
</script>
Also when the term is in the field and I hit the enter key it highlights the verbiage, but when I hit the delete key it unmarks the content, but the full string is removed along with the highlight. I want it to remove "all" highlights on delete or backspace key, but not remove the full string from the input field. Not sure why its removing everything in the input field.
<script>
$input.keydown("input", function(e) {
if (e.keyCode === 46 || e.keyCode === 8) {
$content.unmark();
$input.val(" ").focus();
}
});
</script>
I have created a codepen of my code here: https://codepen.io/dude12go8/pen/PoYbdXd

Move up by UP key from textarea jquery

In html form we need to move up or down using arrow keys to shift focus in the fields. following code works fine for all input elements. but in case of textarea there could be multiple lines so, if we move up or down cursor moves up or down in the textarea itself.
Now, I'm not getting how to move up the focus, if the cursor reaches in the first line of the textarea while pressing up arrow OR move down the focus if the cursor reaches at the end or in the last line of the textarea while pressing down arrow key.
Here is my partial code:
var INPUT_SELECTOR = ':input:enabled:visible';
var inputs = $(INPUT_SELECTOR)
$("form").on("keypress", "input", function(event){
// i is current input
if(event.keyCode === 38){ //action == 'up'
inp = inputs[i > 0 ? parseInt(i) - 1 : inputs.length - 1];
}
if(event.keyCode === 40){ //action == 'down'
inp = inputs[i < inputs.length - 1 ? parseInt(i) + 1 : 0];
}
// focus on the input
moveFocusTo(inp);
});
Our requirement for the up and down arrow keys is same as tab and shift+tab behaviour. everything is done, we have just stuck at textarea.
Sounds like you need to use
https://developer.mozilla.org/en-US/docs/Web/API/event.relatedTarget#1003983
event.relatedTarget
Then you can check to see during the event what element the user is focused on and act accordingly.

Backspace (deleting characters) not working properly in Firefox due to Javascript

I am writing some Javascript/Jquery for a co-worker that is supposed to edit text in a textfield as the user is typing. The purpose of the code is to add formatting to a string of characters (in particular, formatting strings of twelve characters into a valid formatted mac address), however on Firefox I am unable to use the backspace to delete characters once they have been entered into the textfield.
Here is the code that does the formatting:
$(document).ready(function () {
var length = 0;
$("#mac_input").focusin(function (evt) {
$(this).keypress(function () {
content = $(this).val();
content_pre_format = content.replace(/\:/g, '');
content_formatted = content_pre_format.replace(/\n/g, '');
var text_input = $('#mac_input');
if (content_formatted.length % 12 == 0 && length != 0) {
text_input.val(text_input.val() + "\n");
}
length = content_formatted.length % 12;
if (length % 2 == 0 && length != 0) {
if (text_input.val().charAt(text_input.val().length - 1) == ':') {
} else {
text_input.val(text_input.val() + ':');
}
}
});
});
});
Edit: I figured out more about the bug. When I start typing, lets say "abc", right when I type the "c" the script edits the field to show "ab:c". I can backspace the "c" and the ":" but no more. At this point the text field shows "ab", however if I use ctrl-a to select all, the text field changes to "ab:"
here's a more robust solution (current solution will break if a user starts deleting anywhere except the end of the stirng):
$(document).ready(function() {
$("#mac_input").keydown(function (event) {
if (!((event.which > 47 && event.which < 71) || (event.which > 95 && event.which < 106))) {
event.preventDefault();
}
});
$("#mac_input").keyup(function () {
var content=$(this).val();
content = content.replace(/\:/g, '');
content = content.replace(/\n/g, '');
content = content.replace(/(\w{12}(?!$))/g, '$1\n').replace(/(\w{2}(?!\n)(?!$))/g, '$1:')
$(this).val(content);
});
});
it ensures the string is always parsed as a collection of MAC addresses
to explain, it uses to regular expressions,
([abcdef0123456789]{12}(?!$)) matches any sequence of twelve characters that can conform a MAC address and aren't at the end of the string (that's what the (?!$)) lookahead does), and replaces it with the matched string and an appended newline, then it matches any sequence of 2 MAC address characters (([abcdef0123456789]{2}) that aren't immediately followed by a new line or the end of the string ((?!\n)(?!$)).
Just check this: if(event.key == "Backspace") {return;} at the beginning of your keypress handler, and you should be fine.
NB: You have to add the event argument to your keypress handler function.

Change div value based on textbox value using jQuery

I created this fiddle that the div value changes based on your dropdown list selection. http://jsfiddle.net/qSkZW/20/
I want to take it one step further and this is to create a textbox field that if you add for example the number 2 it will change the div value to 240 (in real the 120 you find in the script it will be a php var). If it writes 3 then to 360.
Additionally there must be two limitations.
Prevent them from using non-numeric characters.
The maximum number is pre-configured (from a php variable). Like if the max value is set to 10, if the user writes 30 it will return to 10.
Thank you for your help.
Okay, so first, create a textfield (example id="textfield"), then modify your listener's action to
$("#quantity").change(function () {
var price = parseInt($(this).val(), 10)*120
$("#textfield").attr('value="'+price+'"');
# sets the default value of #textfield to the selection from #quantity
})
.change()
$("#textfield").blur(function () {
# when the element looses focus (they click/tab somewhere else)
var valid = /^\d{2}$/;
# this means any 2 numbers. change {2} to {3} or however many digits.
# you can also also use d[0-10] to identify a range of numbers.
if ( $(this).text() != valid ) {
$("#message").text("Only numbers please!");
$("#message").fadeIn();
# add <span id="message" style="display:none;"></span> next to #textfield
# enclose #textfield & #message in the same element (like <li> or <div>)
}
else {
$("#message").fadeOut();
}
});
Could you please provide more info about #2 (I don't have a clear understanding of what is supposed to happen)
Quick question: why are you trying to put a price in an editable element?
This will do it: http://jsfiddle.net/ebiewener/pBeM8/
You bind the keydown event to the input box in order to prevent the undesired characters from being entered, and bind the keyup event in order check the value & modify the div's height.
$('input').keydown(function(e){
if(!(e.which >= 48 && e.which <=58) && e.which !== 8 && e.which !== 46 && e.which !== 37 && e.which !== 39){ //prevent anything other than numeric characters, backspace, delete, and left & right arrows
return false;
}
})
.keyup(function(){
val = $(this).val();
if(val > 10){
val = 10;
$(this).val(10);
}
$('div').height(val * 10);
});
var max = 30;
$('input').keyup(function() {
var v = $(this).val();
v = isNaN(v)?'':v;
v = v > max ? max : v;
$(this).val(v);
$('div').html(v * 120);
});
http://jsfiddle.net/vWf2x/2/

TextArea with 10 lines and 35 characters per line

I have an HTML page with many elements. The page is scrollable, that means the page has a scrollbar in it. Down to the page I have a HTML textarea with a specified rows and columns attribute.
Now I want a simple JavaScript solution which will help me to validate the the following points each time user enters any character:
The number of lines in the textarea is not greater than 10
Each line has less than or equal to 35 characters
If user crosses 35 character limit for any particular line then the 36th character will be automatically start from next line only if the total line numbers does not exceed 10, else it will show an error popup message and stops there.
User should be able to modify any lines(it may be last line or any middle lines) and still should follow all the above 3 points.
I used the following to limit the amount of characters allowed in my textarea.
This not only counts the amount of characters it trims it if it gets to the end and it also writes out how many characters you have left.
I think all you need to do now is figure out how to add a new line (try something like text += "\r\n";) <- Not 100% sure on this peice.
function textCounter(txtfield, cntFld, maxlimit){
var field = document.getElementById(txtfield);
var countfield = document.getElementById(cntFld);
if (field.value.length > maxlimit) // if too long...trim it!
{
field.value = field.value.substring(0, maxlimit);
}else { // otherwise, update 'characters left' counter
countfield.innerHTML = maxlimit - field.value.length;
}
}
I have done a similar case :
MaxLenght of textarea = 1875 ;
MaxLenght of row = 75 ;
Disable Enter, because over 75's multiple, SW automatically wrap text ;
This is it, with onkeydown trigger:
function wrapTextArea(event,id,maxLineLenght){
// delete and canc
if((recuperaKeyCode(event)!=8) && (recuperaKeyCode(event)!=46)) {
var field = document.getElementById(id).value;
var nextIndex = 0;
for(var i=0; field.length>nextIndex; i++){
nextIndex=maxLineLenght*(i+1)+i;
if(field.length==nextIndex){
if(field.charAt(nextIndex)!= "\n"){
field=field.substring(0, nextIndex)+"\n"+field.substring(nextIndex, field.lenght);
}
}
}
document.getElementById(id).value = field;
}
}
This is how I disabled enter key, where key = 13 :
function disableKey(event,key){
if(recuperaKeyCode(event)==key){
event.preventDefault();
}
}

Categories