I have a textarea. I restrict users to enter only 100 characters in that textarea using jQuery. It works fine..But my code counts space also. I don't want my function to count space as a character. All other inputs from keyboard be counted as a character excluding space.
Here's my jQuery function.
$(document).ready(function(){
var totalChars = 100; //Total characters allowed in textarea
var countTextBox = $('#counttextarea') // Textarea input box
var charsCountEl = $('#countchars'); // Remaining chars count will be displayed here
charsCountEl.text(totalChars); //initial value of countchars element
countTextBox.keyup(function() { //user releases a key on the keyboard
var thisChars = this.value.replace(/{.*}/g, '').length; //get chars count in textarea
if(thisChars > totalChars) //if we have more chars than it should be
{
var CharsToDel = (thisChars-totalChars); // total extra chars to delete
this.value = this.value.substring(0,this.value.length-CharsToDel); //remove excess chars from textarea
}else{
charsCountEl.text( totalChars - thisChars ); //count remaining chars
}
});
});
my HTML Code is given below:
<textarea name="counttextarea" id="counttextarea" cols="30" rows="8"></textarea><br />
<span name="countchars" id="countchars"></span> Characters Left
Here's a fiddle http://jsfiddle.net/6C8zn/
Your regular expression is not correct.
Instead of
var thisChars = this.value.replace(/{.*}/g, '').length; //get chars count in textarea
Use either of these
var thisChars = this.value.replace(/ /g, '').length;
var thisChars = this.value.replace(/\s/g, '').length;
DEMO
Related
I'm trying to create an input bar that suggest tags.
We can enter differents tags by separating them with a white space.
I'm using a datalist to suggest tags, and I developped it to only match the characters after the last white space (e.g.: if I input "stack overfl", the datalist will suggest tags that match with "overfl").
It works well with the first tag, but at the moment I enter a white space, the datalist will update itself correctly but won't show. Does anyone know how to fix this ?
Here is my code for updating the datalist.
$("#tagInput").keypress(function (e) {
//Get value of input element
var input = $(this).val() + String.fromCharCode(e.which);
//Remove every characters before the last white space
while(input.indexOf(' ') > 0) {
input = input.substr(input.indexOf(' ') + 1);
}
console.log(input);
//suggest = datalist
var suggest = $("#suggest");
//Removing every elements from datalist
suggest.empty();
//Get every matching tags
var suggestion = getSuggestion(input);
for(let i = 0; i < suggestion.length; i++)
suggest.append("<option value='"+suggestion[i]+"'></option>");
})
function getSuggestion(input){
var result = [];
for(let i = 0; i < window.tagList.length; i++){
if(window.tagList[i].toLowerCase().includes(input.toLowerCase(), 0))
result.push(window.tagList[i]);
}
return result;
}
I am having trouble creating a code in javascript to limit characters in an input box and trim whitespace. I am asked to use document.getElementById(, onkeyup event handler, and String.split().
I could only do this:
<script>
TextareaElement(document.getElementById("myWordsToCount"));
myTextareaElement.onkeyup = function(){
var maxlimit = 20;
var counter = maxlimit - information.value.split(/^\s+|\s+$/gm,'').length;
}
</script>
I am so new to javascript and I am thinking it might not be my zone. Anyways, I would deeply appreciate any help I could get.
Thanks
For limiting length you should use maxlenght like
input type="text" maxlength="20"
And for trim
var a =document.getElemenyById("YourId").value;
var str=a.trim();
This could be done with Jquery instead of typical JavaScript.
You could do it like :
//Now Assuming your text area has an id of "#text"
var text = document.getElementById('#text').val();
var trim = $.trim(text);
var characters = 100; //you could change the number of characters you want
$("#counter").append("You have <strong>"+ characters+"</strong> characters remaining");
$("#text").keyup(function(){
if($(this).val().length > characters){
$(this).val($(this).val().substr(0, characters));
}
var remaining = characters - $(this).val().length;
$("#counter").html("You have <strong>"+ remaining+"</strong> characters remaining");
if(remaining <= 10)
{
$("#counter").css("color","red");
}
else
{
$("#counter").css("color","black");
}
You could also turn the above code into a function so that you could call this every time the user enter some text in the textbox.
I am trying to create a function that will take an element's text, cut off any characters beyond 80, and add an ellipses if necessary. Here's my code so far:
var maxLength = 80;
function shorten(element) {
var text = $('#' + element).text();
var ret = text;
if (text.length > maxLength) {
text = text.substr(0,maxLength-3) + "...";
}
$('#' + element).text(text);
}
shorten('slide1');
So, the function should take the element, remove extra text off the end, add an ellipses, and then replace the old text in the element with the new string I've just created.
When I run the function, I don't get any errors, but it doesn't actually cut off the text as it should. Why is this?
var text = "Some Text Goes Here. La La La La!";
var textLength = 10; // Number of characters to cut off after
function shorten(text, textLength){
if(text.length > textLength){
text = text.substring(0, textLength) + '…';
}
return text;
}
var shortText = shorten(text, textLength);
Also, using the HTML character for ellipsis is better than using three periods.
I've added a Codepen showing the code working. Additionally, I added a function spaceShorten that will split your text at the last occurrence of a space that is less than the length provided, so you don't split the text mid word.
http://codepen.io/supah_frank/pen/EaYzNz
I have a div tag with contenteditable set to true.
I am trying to find out the last entered word in the div.
For example, if I type in This is a test and I hit a space, I want to be able to get the word test
I want to be able to use this logic so that I can test each word being typed (after the space is pressed).
It would be great if someone could help me with this.
An easy solution would be the following
var str = "This is a test "; // Content of the div
var lastWord = str.substr(str.trim().lastIndexOf(" ")+1);
trim might need a shim for older browsers. (.replace(/\s$/,""))
To strip punctuation like " Test!!! " you could additionally do a replace like following:
lastWord.replace(/[\W]/g,"");
You might want to do a more specific definition of the characters to omit than \W, depending on your needs.
If you want to trigger your eventhandler also on punctuation characters and not only on space, the last replace is not needed.
You first have to know when the content is edited. Using jQuery, that can be done with
$("div").on("keyup", function(){ /* code */ });
Then, you'll have to get the whole text and split it into words
var words = $(this).text().trim().split(' ');
And getting the last word is as complicated as getting the last element of the words array.
Here's the whole code
HTML
<div contenteditable="true">Add text here</div>
JavaScript (using jQuery)
$("div").on("keyup", function(){
var words = $(this).text().trim().split(' '),
lastWord = words[words.length - 1];
console.log(lastWord);
});
Demo
This is the ultimate way:
// listen to changes (do it any way you want...)
document.querySelectorAll('div')[0].addEventListener('input', function(e) {
console.log( getLastWord(this.textContent) );
}, false);
function getLastWord(str){
// strip punctuations
str = str.replace(/[\.,-\/#!$%\^&\*;:{}=\_`~()]/g,' ');
// get the last word
return str.trim().split(' ').reverse()[0];
}
DEMO PAGE
You can try this to get last word from a editable div.
HTML
<div id='edit' contenteditable='true' onkeypress="getLastWord(event,this)">
</div>
JS
function getLastWord(event,element){
var keyPressed = event.which;
if(keyPressed == 32){ //Hits Space
var val = element.innerText.trim();
val = val.replace(/(\r\n|\n|\r)/gm," ");
var idx = val.lastIndexOf(' ');
var lastWord = val.substring(idx+1);
console.log("Last Word " + lastWord);
}
}
Try this link http://jsfiddle.net/vV2mN/18/
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();
}
}