I'm wanting to create a similar thing to the character counter on this website - https://character-counter.uk/. However, instead of counting every character I only want to count hashtags. So if I entered #happy and #sad the counter would return the number 2.
I'm new to javaScript and jQuery so am not sure how I could get this to happen.
Say I have this html
<textarea rows="16" class="form-control"></textarea>
<div class="remaining-counter">Characters Counted: <span
class="well text-well">0</span></div>
I want the 0 belonging to the text-well span to jump up once whenever a hashtag is typed into the text area.
I've been tinkering around with some things but so far can only come up with this code
var count = 0;
$("textarea").on("input", function() {
if ($(this).val().match(/#/)) {
$('.text-well').html(count++);
} else {
return;
}
});
When entering it into the character counter site using the console the counter still counts up whenever I start typing into the textarea and then resets and starts counting up in twos when a # is entered.
Any help is appreciated.
To achieve this you can simply use the match() method to find the number of hashtags within the value of the given textarea, something like this:
$("textarea").on("input", function() {
var text = $(this).val();
var count = (text.match(/(^|\W)(#[a-z\d][\w-]*)/g) || []).length;
$('.text-well').html(count);
}).trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea rows="10" cols="40" class="form-control">Lorem #ipsum dolor #sit amet #consectetur adipiscing</textarea>
<div class="remaining-counter">Hashtags Counted: <span class="well text-well">0</span></div>
Note that I got the hashtag regex from this question
var count = 0;
$("textarea").on('change keyup paste', function() {
if ($(this).val().match(/#/)) {
$('.text-well').html(count++);
}
});
This will count hash tags, requiring each pound sign counted to be followed by at least one word character:
$("textarea").on("keyup", function() {
var matches = $(this).val().match(/#\w+\b/g);
var count = matches ? matches.length : 0;
$('.text-well').html(count);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="10" class="form-control"></textarea>
<div class="remaining-counter">Characters Counted: <span
class="well text-well">0</span></div>
Basically:
Instead of trying to keep track of a counter, do the entire count every time.
Use .match(pattern).length to get the number of matches, remembering to use the g flag so you actually count all matches.
If you only want to count hashes, /#/ works fine. If you want to match hash tags, ensure the hashtag is followed by a letter by using /#\w/.
Use the keyup event to ensure your count is updated on every letter press.
Related
I am using a form to build a block of text, the final output of which needs to be kept under a certain character count.
For the user, I need to be able to provide real-time character counting so they can adjust their entries as appropriate.
Basic HTML would be as follows:
<form>
<input type="text" id="#input1">
<input type="text" id="#input2">
</form>
<div class="character-counter">0</div>
However my JS/jQuery is not working very well: while it is outputting a counter in real time, it seems to be concatenating the final results in the output despite me parsing the variables as integers.
$('#input1').keyup(function() {
// Variables
var currentCharCount = parseInt($('.character-counter').text());
var fieldLength = parseInt($(this).val().length, 10);
var newCharCount = fieldLength + currentCharCount;
// Counter output
$('.character-counter').text(Number(newCharCount));
});
$('#input2').keyup(function() {
// Variables
var currentCharCount = parseInt($('.character-counter').text());
var fieldLength = parseInt($(this).val().length, 10);
var newCharCount = fieldLength + currentCharCount;
// Counter output
$('.character-counter').text(Number(newCharCount));
});
The correct solution will update the '.character-counter' div with the correct total character count between the fields every time a character is typed or deleted or pasted in.
Thanks!
You don't want the old value of the character-counter element at all, you purely want to use the lengths of the text in the two inputs. Separately: Don't use keyup, use input. (What if the user right-clicks and pastes? No keyup occurs...)
Separately, the id attributes of your input fields are incorrect: They shouldn't have the # on them.
So (see comments):
// You can hook the event on both fields with the same call
// Note using `input`, not `keyup`
$("#input1, #input2").on("input", function() {
// Get the length of each input's current value, then put it
// in the .character-counter div
$('.character-counter').text($("#input1").val().length + $("#input2").val().length);
});
<form>
<input type="text" id="input1">
<!-- No # here --------^ -->
<input type="text" id="input2">
<!-- Nor here ---------^ -->
</form>
<div class="character-counter">0</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$('#srctxt div').each(function() {
var dari = $('#box').val();
var text = $(this).text();
$(this).html(text.replace(dari, '<b>'+dari+'</b>'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form method="POST">
<input type="text" id="box" value="love"> // working
<input type="text" id="box" value="love girl"> // not working
<div id="srctxt">
<div>i love you</div>
<div>love girl</div>
<div>not love</div>
<div>love love love</div>
</div>
</form>
I'm developing a search site by bolding every matching word of the input word with search results.
If only a word is entered, such as the word love, then this script works quite well. But if using two or more words, then this script does not work properly.
for example the word love girl, then the bold on the results for only one line. but it all contains the word love, so this is a problem for me.
sorry if my English is a bit hard to understand. however, I am asking for suggestions of this jQuery code fix. Thank you...
You can easily do this using regex
Here are the steps:
Step-1. Split the input value to make an array of input words.
Step-2. Iterate over all the div for which you want to execute search/replace condition
Step-3. For each word in input array create a searchregexp and replace if found
if ($('#box').val().length !== 0) {
var dari = $('#box').val().split(' ');
$('#srctxt div').each(function() {
dari.map(item => {
var regex = new RegExp('(' + item + ')(?!>|b>)', 'gi');
$(this).html($(this).html().replace(regex, "<b>$1</b>"));
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="box" value="love girl b">
<div id="srctxt">
<div>i love you</div>
<div>love girl</div>
<div>not love</div>
<div>love love love</div>
</div>
Also I removed the duplicate input field having same id as it is invalid html.
I think you will have to loop through your text in the search field. Assuming no special characters (-,{,}, > etc) are entered you can do following
$('#srctxt div').each(function() {
var dari = $('#box').val().split(" ");
var text = $(this).text();
dar.map((val, index) => {
$(this).html(text.replace(val, '<b>'+val+'</b>'));
});
});
Let me know if this helps.
maybe you have to split your search query, like:
'love girl'.split(' '); // ---> ['love','girl'];
and do a forEach on the resulting array and behave each one like your dari variable.
note that even if your word is one word, (like "love"), the result of split would still be an array. so you do not need to separate your logic into two branches.
I'm trying to duplicated the following code but no matter what combination I attempt I cannot get the second copy of it working. Basically I have two html textarea boxes that I need to character count on the same page. They can actually have the same exact count if it makes it easier, I'm not just sure how to duplicate the JS and still have it function.
function countChars(countfrom,displayto) {
var len = document.getElementById(countfrom).value.length;
document.getElementById(displayto).innerHTML = len;
}
<textarea id="data"
onkeyup="countChars('data','charcount');"
onkeydown="countChars('data','charcount');"
onmouseout="countChars('data','charcount');"></textarea>
<span id="charcount">0</span> characters entered.
You have to make new textarea with other id and span to display characters count, also with other id. Then you use same function to count charaters, but with other ids
function countChars(countfrom,displayto) {
var len = document.getElementById(countfrom).value.length;
document.getElementById(displayto).innerHTML = len;
}
<textarea id="data" onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea>
<span id="charcount">0</span> characters entered.
<textarea id="data2" onkeyup="countChars('data2','charcount2');" onkeydown="countChars('data2','charcount2');" onmouseout="countChars('data2','charcount2');"></textarea>
<span id="charcount2">0</span> characters entered.
I have found some code for a chat system. I am going to be using it as a child-friendly (so I can't be blamed for anything) global chat. The way the code works is by checking the input to see if it contains any word from an array, if it does then the program will display something to a <ol> tag, for me to see if it works. Otherwise is does nothing.
JQUERY
var banned_words = {
'songs': ['hello', 'sorry', 'blame'],
'music': ['tempo', 'blues', 'rhythm']
};
function contains(words) {
return function(word) {
return (words.indexOf(word) > -1);
};
};
function getTags(input, banned_words) {
var words = input.match(/\w+/g);
return Object.keys(banned_words).reduce(function(tags, classification) {
var keywords = banned_words[classification];
if (words.some(contains(keywords)))
tags.push(classification);
return tags;
}, []);
};
// watch textarea for release of key press
$('#sendie').keyup(function(e) {
$('#tags').empty();
var tags = getTags($(this).val().toLowerCase(), banned_words);
var children = tags.forEach(function(tag) {
$('#tags').append($('<li>').text(tag));
});
if (e.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
// send
if (length <= maxLength + 1) {
chat.send(text, name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
HTML
<form id="send-message-area">
<p style="text-align:center">Your message: </p>
<input id="sendie" maxlength = '100' />
</form>
<ol id="tags">
</ol>
But, what I'm also wanting to do is check if the input value contains phrases from the array so I can ban phrases that are too sensitive for children. How can I add this in, or is there another more efficient way to check the input?
UPDATE
I have already tried to place the phrase directly into the banned_words (I changed them as this post would get flagged for inappropriate language) and using the hexadecimal character for the space-bar. None of these worked.
You can try either of the following since the space is also a known charachter:
test 1:
Just put your phrase between quotes such as 'cry baby','red apple' etc.
sometimes it does not work, you can try
test 2:
replace the space with the hexidecimal character \x20 such as 'cry\x20baby','red\x20apple'
I hope one or both of these works for you.
I have done some more research and have found a cool plugin for JQuery. It's called jQuery.profanityFilter. It uses a json file filled with sensative words.
Link to github download: https://github.com/ChaseFlorell/jQuery.ProfanityFilter
How do I work out in jQuery a character counter of a p/div tag?
Basically i want to show a different css value IF the character value >=50.
Been struggling for hours with it :)
Use
$("#myDiv").text().length;
var $div = $('#mydiv');
if($div.text().length >= 50) {
$div.addClass('class');
}
Put a "long" class on all div and p elements with more than 50 characters:
$("p, div").filter(function(){
return $(this).text().length >=50;
}).addClass('long');
If you don't know how much content you have, though, then presumably this content is generated dynamically by the server, right? And if this is the case, wouldn't it make more sense to have the server—which knows how much content it's plopping into these containers—add the class dynamically while generating the page to send? Why rely on jQuery?
Try this snippet it works even if the text's length was greater than 50 characters.
You can also calculate the character digits of the paragraph. (Excluding new lines and space bars)
window.setInterval(function() {
var txt = $("#txt").val();
var parLength = $("#data").text().length;
var charLength = txt.replace(/ /g, '').replace(/\n/g, '').length;
$("#data").text(txt);
$("#calcLength").text("The paragrapgh's length is: " + parLength);
$("#calcChar").text("The amount of characters is: " + charLength);
}, 10);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="txt" placeholder="Enter text here..." style="height:100px;width:250px"></textarea>
<p id="data"></p>
<p id="calcLength"></p>
<b>Note: even a space character is calculated through the length function</b>
<p id="calcChar"></p>
<b>Note: a space bar,and every empty line is trimmed in the second calculated value</b>
I have provided this example to make it simple for use and compatability.