How to integrate counting frequency of characters in a string using javascript - javascript

I have some simple HTML code
<textarea id="text" placeholder="Type text...."></textarea>
<a id="button" class="button"></a>
<textarea id="result" disabled></textarea>
and I have a javascript code
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
I just want to integrate js with HTML to count each character frequency inside of textarea with id="text" and show result inside of textarea with id="result". I have tried to use
document.getElementById("text").value;
but something goes wrong and still not working. There is any way to do this in easy way?

If you want to do it while typing you can use the keyup event on the textarea, in the following way
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
window.addEventListener('load', function() {
const textbox = document.getElementById('text');
const result = document.getElementById('result');
textbox.addEventListener('keyup', function() {
const frequency = getFrequency( textbox.value );
result.value = Object.keys( frequency ).map( key => `${key}: ${frequency[key]}` ).join('\n');
});
});
<textarea id="text" placeholder="Type text...."></textarea>
<a id="button" class="button"></a>
<textarea id="result" disabled></textarea>
if you want to do it upon button click, you could change the previous code like so:
document.getElementById('button').addEventListener('click', function() {
const frequency = getFrequency( textbox.value );
result.value = Object.keys( frequency ).map( key => `${key}: ${frequency[key]}` ).join('\n');
});

This should do it.
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
document.getElementById('myButton').onclick = function(){
var str = document.getElementById('text').value;
var result = getFrequency(str);
document.getElementById('result').value = JSON.stringify(result);
}
<textarea id="text" placeholder="Type text...." ></textarea>
<button id="myButton" class="button">Count</button>
<textarea id="result" disabled></textarea>

Using spread syntax, Map, Array#reduce, and String#split
const textArea = document.getElementById("text");
const button = document.getElementById("button");
const result = document.getElementById("result");
button.addEventListener("click", function(){
const value = textArea.value.trim();
const res = getFrequency(value);
console.log(JSON.stringify([...res]));
result.innerText = `(${[...res].join("), (")})`;
})
function getFrequency(str){
return str.split("").reduce((a,c)=>a.set(c, (a.get(c) || 0) + 1), new Map());
}
div {
display: flex;
background-color: lightgrey;
flex-direction: column;
}
div > div {
flex-direction: row;
}
<div>
<textarea id="text" placeholder="Type text....">
Some text to check the count of characters
</textarea>
<div>
<button id="button" class="button">Click me</button>
<p id="result"></p>
</div>
</div>

Related

How can I take text from <input> tag to javascript

I have made a program and it prompts the user to input text. Is there a way I can just take user input from the text box and then have the program take and use that text from there? Here's the code so far:
None of your corrections were working because I didn't tell you the what this program does. This program is supposed to take in a letter and then replace it with another letter encrypting the text, so I think that you need to see the entire code to figure this out;
function encodeFunction() {
var text = prompt("Enter Text");
document.getElementById("function").innerHTML = LetterChanges(text);
}
function decodeFunction() {
var text = prompt("Enter Text");
document.getElementById("function").innerHTML = LetterChanges(text, false);
}
function LetterChanges(str, encode = true) {
let adjust = 1;
if (!encode) {
adjust = -1;
}
}
}
str = str.toLowerCase();
let strArray = str.split("");
let letterChange = strArray.map(function(value, index, array){
if(str.charCodeAt(index) < 97 || str.charCodeAt(index) > 122){
return value
}else{
return String.fromCharCode(str.charCodeAt(index)+adjust)
}
});
return letterChange.join("");
}
<form>
<input type="text" id="EString" name="EString"> <br><br>
</form>
<button onclick="encodeFunction()">Encode String</button>
<button onclick="decodeFunction()">Decode String</button>
<p id="function"></p>
In your encode and decode functions, you can change:
var text = prompt("Enter Text");
to
var text = document.getElementById("EString").value;
If you'd like to get the value of the text input(id='EString') you can use
document.getElementById('EString').value
You could simply get the value of document.getElementById("EString"), e.g.
function encodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text);
}
function decodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text, false);
}
function LetterChanges(str, encode = true) {
let adjust = 1;
if (!encode) {
adjust = -1;
}
return str;
}
<form>
<input type="text" id="EString" name="EString"> <br><br>
</form>
<button onclick="encodeFunction()">Encode String</button>
<button onclick="decodeFunction()">Decode String</button>
<p id="function"></p>
function myChange(){
console.log(document.getElementById("EString").value);
}
<form>
<input type="text" onchange="myChange()" id="EString" name="EString" style=" width:1000px; height:500px;"></input>
</form>
Check the below code for your desired result:
function encodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text);
}
function decodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text, false);
}
function LetterChanges(str, encode=true) {
let adjust = 1;
if(!encode){
adjust = -1;
}
return adjust;
}
<form>
<input type="text" id="EString" name="EString" style=" width:1000px; height:500px;" /> <br><br>
</form>
<button onclick="encodeFunction()">Encode String</button>
<button onclick="decodeFunction()">Decode String</button>
<p id="function"></p>
I made some changes in your code.
<button onclick="encodeFunction()">Encode String</button>
<button onclick="decodeFunction()">Decode String</button>
<p id="function"></p>
<script>
function encodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text);
}
function decodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text, false);
}
function LetterChanges(str, encode=true) {
let adjust = 1;
if(!encode){
adjust = -1;
}
return "Text recieved in JavaScript: " + str;
}
</script>
Use oninput and onchange attributes in input tag to call javascript function, because oninput is not working in some browsers.

Element text not changing when passing selected textContent and new value to an update function

I'm creating a CRUD page where the user can add, delete and edit text, but I have an issue in updating the text after I select it for edit.
In editText function when I click the edit button the text that was added will pop up inside the input field. When I click on the update button (triggering the updateText function), I can see the text in console log but the corresponding html is not updated.
HTML
<div class="main">
<form>
<input type="text" placeholder="search">
</form>
<ul></ul>
<div>
<input class="add-text" type="text" placeholder="Add Text">
<button id="add">Add</button>
<button id="update">update</button>
</div>
</div>
Javascript
const inputsearch = document.querySelector('form input');
const addInputBtn = document.querySelector('#add');
const update = document.querySelector('#update');
addInputBtn.addEventListener('click', addtext);
function addtext(){
let li = document.createElement('li');
let inputadd = document.querySelector('.add-text');
let addedtext = inputadd.value;
let h1Tag = '<h1 id="text">'+addedtext+'</h1>';
let tags = h1Tag + '<button id="delete">Delete</button><button id="edit">Edit</button>';
if(addedtext == ''){
alert('please add some text');
return;
}else{
li.innerHTML = tags;
document.querySelector('ul').appendChild(li);
}
li.querySelectorAll('#delete')[0].addEventListener('click', deleteText);
li.querySelectorAll('#edit')[0].addEventListener('click', editText);
getlist(li, h1Tag);
inputadd.value = '';
}
function deleteText(e) {
e.target.parentNode.remove();
document.querySelector('.add-text').value = '';
}
function editText(e) {
let currentText = e.target.parentNode.firstChild.textContent;
let currentValue = document.querySelector('.add-text');
currentValue.value = currentText;
getupdate(currentText, currentValue);
}
function getupdate(currentText, currentValue) {
update.addEventListener('click', updateText);
function updateText() {
currentText = currentValue.value
console.log(currentText = currentValue.value);
}
}
function getlist(li, h1Tag) {
inputsearch.addEventListener('keyup', serchText);
function serchText(e) {
let typetext = e.target.value.toLowerCase();
if(h1Tag.toLowerCase().indexOf(typetext) != -1){
li.style.display = 'block';
}else{
li.style.display = 'none';
}
}
}
To solve the issue without changing your overall approach, your edit button click needs to get the corresponding element (not just its textContent) and pass it to your getupdate() function to be updated when your update button is clicked. Relatively minor changes to your current functions:
function editText(e) {
const currentText = e.target.parentNode.firstChild;
const currentValue = document.querySelector('.add-text');
currentValue.value = currentText.textContent;
getupdate(currentText, currentValue);
}
function getupdate(currentText, currentValue) {
update.addEventListener('click', updateText);
function updateText() {
currentText.textContent = currentValue.value;
}
}
There are some other issues with your code, particularly the creation of multiple elements with the same id (which is malformed and will likely become problematic as you add additional features). Following is a snippet that addresses that issue as well as simplifying some of your functions and fixing the search.
const search = document.querySelector('form input');
const input = document.querySelector('.add-text');
const container = document.querySelector('ul');
let items = null;
let currentItem = null;
const searchItems = (event) => {
if (items) {
const s = event.currentTarget.value.toLowerCase();
for (const item of items) {
if (item.firstChild.textContent.toLowerCase().indexOf(s) !== -1) {
item.style.display = 'block';
} else {
item.style.display = 'none';
}
}
}
};
const deleteItem = (event) => {
currentItem = null;
event.currentTarget.parentNode.remove();
};
const editItem = (event) => {
currentItem = event.currentTarget.parentNode.firstChild;
input.value = currentItem.textContent;
};
const updateItem = () => {
if (currentItem) {
currentItem.textContent = input.value;
}
};
const addItem = () => {
let val = input.value
if (val) {
const li = document.createElement('li');
let inner = '<h1 class="text">' + val + '</h1>';
inner += '<button class="delete">Delete</button>';
inner += '<button class="edit">Edit</button>';
li.innerHTML = inner;
container.appendChild(li);
val = '';
currentItem = li.firstChild;
items = document.querySelectorAll('li');
for (let del of document.querySelectorAll('.delete')) {
del.addEventListener('click', deleteItem);
}
for (let edit of document.querySelectorAll('.edit')) {
edit.addEventListener('click', editItem);
}
} else {
alert('please add some text');
return;
}
};
search.addEventListener('keyup', searchItems);
document.querySelector('#add').addEventListener('click', addItem);
document.querySelector('#update').addEventListener('click', updateItem);
<div class="main">
<form>
<input type="text" placeholder="Search">
</form>
<ul></ul>
<div>
<input class="add-text" type="text" placeholder="Add Text">
<button id="add">Add</button>
<button id="update">Update</button>
</div>
</div>

Remove line with specific word from text area using javascript

I am trying to remove line with specific word using javascript from textarea.
Here is example
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
If the user enters the value in input field the line which contains it should be removed. Suppose user enters CxPh1tgiK2g or xOYPv7CxMVk the line which contains those ids should be removed
Try
$("#remove").click(function() {
var text = $("#id").val()
var lines = $('#textarea').val().split('\n');
lines = lines.filter(function(val) {
if (val.match(text)) return false
else return true
})
$('#textarea').text(lines.join('\n'))
})
$("#replace").click(function() {
var text = $("#id").val()
var lines = $('#textarea').val().split('\n');
var n = Math.floor(Math.random()*lines.length)
lines[n] = lines[n].replace(/\?v=([A-Za-z0-9]){11}/, "?v="+text)
$('#textarea').text(lines.join('\n'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="id" />
<input type="button" id="remove" value="Remove" />
<input type="button" id="replace" value="Replace" />
<br/>
<textarea id="textarea" rows="4" cols="150">
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
</textarea>
As solution to remove line with inclusion
var value = test.value.split(/\n/g).filter(function(val)
{
return val !== "";
});
console.log(value);
setTimeout(function()
{
var index = value.findIndex(function(val)
{
return val.includes('kKC7-ACrs1w');
});
if (index !== -1)
{
value.splice(index, 1);
test.value = value.join("\n");
}
}, 2000);
.text {
width: 100%;
resize: none;
height: 200px;
}
Line with <b>kKC7-ACrs1w </b>will be removed in 2 secs
<textarea name="" id="test" class=text >
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
</textarea>
You can do something like this:
var ta = document.querySelector("textarea");
var lines = ta.innerHTML.split("\n");
var id = "omg";
for (var i = 0; i < lines.length; i ++) {
if (lines[i].indexOf(id) > -1) {
lines.splice(i, 1);
}
}
ta.innerHTML = lines.join("\n");
<textarea>
lol
omg
js
</textarea>

How to skip converting element text

i want output text oldnames not changes if user insert text 'false'
for example:
user input text "false toni" in textbox.
and i want output still "false toni"
why my code still changes text "toni" with "rina"?
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni','rian'];
var newNames = ['rina','susi'];
if (oldNames== 'false ' + oldNames){
document.getElementById("check").innerHTML = x.replaceArr(oldNames, oldNames);
}else{
document.getElementById("check").innerHTML = x.replaceArr(oldNames, newNames);
}
}
</script>
<body>
ENTER TEXT: <br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>
UPDATE:
Improve the question:
Trying enter text "My name is rian and my name is false toni" .
Posible to make output "rian" still change to "susi"?
use includes x.includes(value) to check whether the text area value contains a word that you want to replace . if it contains false then your oldnames not get changed.
If you are using IE then use x.indexOf(value)>0 instead of x.includes(value)
http://www.w3schools.com/jsref/jsref_includes.asp
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni', 'rian'];
var newNames = ['rina', 'susi'];
oldNames.forEach(function(value, index) {
/*if (x.includes('false '+value)){
var oldNames1=['false '+value];
x = x.replaceArr(oldNames1, oldNames1);
}*/
if (x.includes(value)) {
var oldNames1 = [value];
x = x.replaceArr(oldNames1, newNames[index]);
newNames1 = ['false ' + newNames[index]];
oldNames1 = ['false ' + value];
x = x.replaceArr(newNames1, oldNames1);
}
});
document.getElementById("check").innerHTML = x;
}
</script>
<body>
ENTER TEXT:
<br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>
You false checking condition is wrong, you can do it using substr:
if (x.substr(0, 6) === 'false ') {
// The string starts with false
} else {
}
You can find more details on the substr from MDN.
UPDATE: As mentioned in the comment same can be done via startsWith and this is a better approach.
if (x.startsWith('false ')) {
// The string starts with false
} else {
}
try this. Compare array values instead of array.
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni','rian'];
var newNames = ['rina','susi'];
if (x.indexOf('false') > -1 ){
document.getElementById("check").innerHTML = x.replaceArr(oldNames, oldNames);
}else{
document.getElementById("check").innerHTML = x.replaceArr(oldNames, newNames);
}
}
</script>
<body>
ENTER TEXT: <br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>

how to use javascript onkeyup for multiple ids at sametime

I have 2 html textbox for users to enter numbers. To sum those numbers, I am passing the values to JavaScript variable and after addition displaying the result to html div section
<div class="input-left"><span><input class="textbox" id="left" name="count" type="text" size="5" value="" /></span></div>
<div class="input-right"><span><input class="textbox" id="right" name="count" type="text" size="5" value="" /></span></div>
<div id="result"> </div>
javascript:
document.getElementById('left').onkeyup = function() {
var a = parseFloat(this.value);
}
document.getElementById('right').onkeyup = function() {
var b = a + parseFloat(this.value);
document.getElementById("result").innerHTML = b || 0 ;
}
But I have an issue with JavaScript. It not displaying the result. How to add both functions in same onkeyup function.
FIDDLE SETUP
Try this:
window.onload = function(){
var left = document.getElementById('left');
var right = document.getElementById('right');
var result = document.getElementById("result");
left.onkeyup = calc;
right.onkeyup = calc;
function calc() {
var a = parseFloat(left.value) || 0;
var b = parseFloat(right.value) || 0;
result.innerHTML = a + b ;
}
}
JSFiddle: http://fiddle.jshell.net/gYV8Z/3/
Update: To hide the result in case the sum equals zero , change the last line like this:
result.innerHTML = ( a + b ) || "";
JSFiddle: http://fiddle.jshell.net/gYV8Z/4/
document.getElementById('left').onkeyup = function() {
var a = parseFloat(this.value);
}
document.getElementById('right').onkeyup = function() {
var b = a + parseFloat(this.value);
document.getElementById("result").innerHTML = b || 0 ;
}
it your code, var a is local variable. make it global variable.
but i would use this code.
function add(){
return parseFloat(document.getElementById('left').value) + parseFloat(document.getElementById('right').value);
}
document.getElementById('left').onkeyup = function() {
document.getElementById("result").innerHTML = add();
}
document.getElementById('right').onkeyup = function() {
document.getElementById("result").innerHTML = add();
}

Categories