Javascript Character Counter Duplication - javascript

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.

Related

Program is treating the same string differently when entered into a different text box

I have a program that is supposed to group links together. Like minecraft saved toolbars, you can save a collection of links, then enter in the name of a group and it will open all of them.
But my program is having trouble with getting the list from localStorage when the name is entered into the text box meant to get the link. But when I just use the value of the text box meant to name the group, it works fine.
My code is here:
var groupName = document.getElementById('name');
var link = document.getElementById('newLink');
var linkCounter = 0
var getByName = document.getElementById('getByName').value
function startGroup() {
localStorage.setItem(groupName.value, groupName.value);
console.log(localStorage.getItem(groupName.value))
}
function addLink() {
linkCounter++;
localStorage.setItem(groupName.value + '_link' + linkCounter, link.value);
console.log(localStorage.getItem(groupName.value + '_link' + linkCounter))
}
function saveGroup() {
localStorage.setItem(groupName.value + '_length', linkCounter);
console.log(localStorage.getItem(groupName.value + '_length'))
alert(groupName.value);
}
function getGroup() {
// if I replace getByName with groupName.value, it works fine.
var len = localStorage.getItem(getByName + '_length')
console.log(len)
for (var x = 1; x <= len; x++) {
window.open(localStorage.getItem(getByName + '_link' + x));
}
}
<!DOCTYPE html>
<html>
<a href='readit.html'>READ THIS BEFORE USING</a>
<p>WHEN ADDING A LINK YOU NEED TO PASTE IT OR ADD HTTPS:// TO THE BEGINNING OF THE LINK.</p>
<div id='toolbars'>
<p>Open a group!</p>
</div>
<div id='create'>
<p>Create some bookmark groups!</p>
<input type='text' placeholder='name your group' id='name'>
<button onclick='startGroup()'>Let's add some links!</button>
<br>
<input type='text' placeholder='add a link' id='newLink'>
<button onclick='addLink()'>Submit</button>
<br>
<button onclick='saveGroup()'>SAVE</button>
</div>
<div id='preview'>
<br><br>
<button onclick='getGroup()'>Open this group</button>
<input type="text" id="getByName">
</div>
</html>
<script src="script.js"></script>
You are reading the value of the getByName input element at page load. Instead you should read the value at the time of need. So define getByName as the DOM element (not as its value):
var getByName = document.getElementById('getByName');
And where you currently reference getByName, suffix the .value property accessor. For instance:
var len = localStorage.getItem(getByName.value + '_length');
Side note: I find it easier to use a memory data structure for all your data, and when something is added to it, to write that complete data structure to one single local storage key, JSON formatted. You may want to look into that.

How do a maintain an accurate character count between input from separate fields using JS?

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>

Search all words in the input field, then replace all matching words in the div tag

$('#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.

Hashtag Counter

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.

Javascript no jquery - Split a textareas single column list (unknown line count) & display in csv's of 150

I am trying to put together what I thought would be an easy solution for a friend.
He has a list of fan emails that he collects at gigs and off his website.
He sticks them in a single column file and saves them.
He needs to have them in comma delimited format containing 150 each, one single line.
He wants a "simple" local HTML form he can paste the list into and have the results displayed.
So, I started working on it but, it has proven past my ability.
So far I have some basics but, I really need help.
As you can see, I am really a beginner.
<html><head>
<script type="text/javascript">
function makeit(){
var enteredEmails = document.getElementById("emails").value;
var cnt = document.getElementById("breakcnt").value;
var mails = enteredEmails.toString();
var textareacnt = '1';
// Now I think I need to loop or create arrays of emails up to cnt //
csvmails = mails.splice(0,cnt)
// Then dynamically generate some textareas or boxes populated with a single comma delimited line of cnt" emails //
document.write("<textarea id=\"textareacnt\">" + csvmails + "</textarea>")
textareacnt++;
}
</script>
</head><body>
<form onsubmit="makeit();">
<textarea name="emails" id="emails" rows="10" cols="75"></textarea><br />
<input type="text" name="breakcnt" id="breakcnt"><br />
<input type="submit" name="submit" value="submit">
</form>
<textarea id="results"></textarea>
</body></html>
The textarera will have emails pasted into it like:
amail1#sometld.com
bmail1#sometld.com
cmail1#sometld.com
amail4#sometld.com
zmail10#sometld.com
... up to 6000 fan emails he has collected over the years
He needs the results to be:
amail1#sometld.com,bmail1#sometld.com,cmail1#sometld.com,amail4#sometld.com,zmail10#sometld.com
up to 150 emails long as I am sure the last chunk or array will not contain 150.
I cant get anything to work and I spent 6 hours on this so far.
Can someone please help? I feel like a complete idiot.
All you have to do is split the text into an array and then splice the array in a loop and join the slices you take out like this:
var emails= document.getElementById('emails').value.split(/\s+/), list="";
while(emails.length) {
list+=emails.splice(0,150).join(',')+"\n";
}
//list now has the result you are looking for
I have made an example of how to this here: http://jsfiddle.net/PfB42/2/
All you have to do is paste the emails into the text area and it will automatically change the format to the one you are looking for, and insert it to the <pre> area below the textarea
This should achieve what you want.
Don't be so hard on yourself mate :)
<html><head>
<script type="text/javascript">
function makeit(){
var enteredEmails = document.getElementById("emails").value;
var results = document.getElementById("results");
var index = 0;
var index2 = enteredEmails.indexOf("\n");
while(true) {
results.value += enteredEmails.substring(index, index2);
index = index2+1;
var index2 = enteredEmails.indexOf("\n", index+1);
//EOF
if(index2 == -1) {
results.value += ",";
results.value += enteredEmails.substring(index, enteredEmails.length);
break;
} else {
results.value += ",";
}
}
}
</script>
</head><body>
<form onsubmit="makeit();">
<textarea name="emails" id="emails" rows="10" cols="75"></textarea><br />
<input type="button" value="submit" onclick="makeit()">
</form>
<textarea id="results"></textarea>
</body></html>
Ouch, don't use that complicated scripts. Strings have functions exactly for that purpose:
var input = document.getElementById("emails").value;
input = input.replace(/\r\n/g, "\n"); // I hate this
var emails = input.split("\n"); // make an Array
var output = emails.join(","); // should we use ", " instead?
Of course you could put everyhing in one line ;-)

Categories

Resources