how to show content in multiple classes with javascript - javascript

I am using tinymce for a textarea and i want to cout the characters inside of it.
Now i use this code:
<textarea class="tinymce" rows="2" cols="20"></textarea>
<br />
<div class="character_count"></div>
<textarea class="tinymce" rows="2" cols="20"></textarea>
<br />
<div class="character_count"></div>
<textarea class="tinymce" rows="2" cols="20"></textarea>
<br />
<div class="character_count"></div>
<script type="text/javascript">
tinymce.init({
selector: '.tinymce',
width: 400,
setup: function (ed) {
ed.on('keyup', function (e) {
var count = CountCharacters();
var x = $(".character_count");
x[0].innerHTML = "Characters: " + count;
});
}
});
function CountCharacters() {
var body = tinymce.activeEditor.getBody();
var content = tinymce.trim(body.innerText || body.textContent);
return content.length;
};
</script>
This works fine, except the number of characters is displayed only in the first div (because of x[0]
is it possible to show, whatever textarea i am typing in, to display the characters in ever div <div class="character_count"></div> ?

Yes, relace this line x[0].innerHTML = "Characters: " + count; with this
x.each( function() { $(this).text("Characters: " + count); });
const p = $("p")
$("input").on("input", function(e) {
p.each(function() {
$(this).text(e.target.value)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" />
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>

Related

how to append input fields to a div without clearing the values with javascript

I have this code that appends a div that contains input fields and textareas to a parent div on click of a button. when I append the div and input some values in the fields and then append a new div, the values of the input fields somehow becomes empty. how can it fix this problem?
here is the code:
let counter = 1;
let new_section = document.getElementsByClassName("addnew")[0];
document.getElementById("shownew").addEventListener("click", (e) => {
e.preventDefault();
new_section.innerHTML += ` <div class="lowerlayer2">
<input type="text" placeholder="Word Type" id="wtype${counter}" />
<input type="text" placeholder="Synonym" id="syn${counter}" />
<input type="text" placeholder="Antonyms" id="anty${counter}" />
<textarea
cols="30"
rows="10"
placeholder="History & Etymology"
id="history${counter}"
></textarea>
<textarea
cols="30"
rows="10"
placeholder="Examples"
id="example${counter}"
></textarea>
<textarea
cols="30"
rows="10"
placeholder="Definition 1"
id="def1${counter}"
></textarea>
</div>`;
counter++;
});
innerHTML += overwrites the entire HTML instead of simply adding to it. Values are not included in the overwrite.
appendChild() will add to the div as expected if you don't mind it inserting an additional node. In your case you are adding a div anyways so its ok.
var newInfo = document.createElement('div'); // this makes a node, a node is require for appendChild. You could also use 'p' or 'span' etc.
newInfo.setAttribute("class", "lowerlayer2"); // you can add your classes and id etc with setAttribute
newInfo.innerHTML = "data to be added/appended";
document.getElementById("newtestdiv").appendChild(newInfo);
Minimal example using insertAdjacentHTML:
let addedCounter = 1;
document.addEventListener("click", handle);
function handle(evt) {
if (evt.target.id === "add") {
return addStuff();
}
}
function addStuff() {
document.querySelector("#container")
.insertAdjacentHTML("beforeend", `
<p>
<input type="text" placeholder="Word Type" id="wtype${addedCounter}" />
</p>`);
addedCounter += 1;
}
<div id="container">
<button id="add">Add stuff</button>
</div>
//get the input elements
let input_one = document.getElementById('INPUT_ONE_ID');
let input_two = document.getElementById('INPUT_TWO_ID');
let input_three = document.getElementById('INPUT_THREE_ID');
let counter = 1;
let new_section = document.getElementsByClassName("addnew")[0];
document.getElementById("shownew").addEventListener("click", (e) => {
e.preventDefault();
// instead of creating new elements, append the old input elements
new_section.innerHTML += ` <div class="lowerlayer2">`+input_one+input_two+input_three+`
<textarea
cols="30"
rows="10"
placeholder="History & Etymology"
id="history${counter}"
></textarea>
<textarea
cols="30"
rows="10"
placeholder="Examples"
id="example${counter}"
></textarea>
<textarea
cols="30"
rows="10"
placeholder="Definition 1"
id="def1${counter}"
></textarea>
</div>`;
counter++;
});

Count characters of dynamically created textareas with different id and name attr

I am having two textareas one under another
<div class="form-group">
<span id="textarea_feedback1"></span>
<span> 🖊Characters left</span>
<br>
<textarea name="answer1" id="answer1" rows="4" placeholder="Type your answer here" areaid="1"></textarea>
<hr>
<span id="textarea_feedback2"></span>
<span> 🖊Characters left</span>
<br>
<textarea name="answer2" id="answer2" rows="4" placeholder="Type your answer here" areaid="2"></textarea>
</div>
Both textareas are created dynamically and they have different id and name attr. At some point, they might be 2, 3, 4... and so on.
What I am trying to do is to create a char counter for each textarea that also applies dynamically.
It would have had been easy if the number of the textareas was fixed (i.e, always 2).
But I am having trouble finding a way to apply one and the same JQuery script to textareas with a different name and id attribute.
I was thinking about adding a unique attribute like areaid="" to each textarea, so I can somehow modify dynamically the script.
This is the script I have
$(document).ready(function() {
var text_max = 400;
$('#textarea_feedback1').html('<span>'+text_max + '</span>');
$('#answer1').on('input click keyup', function() {
var text_length = $('#answer1').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback1').html('<span>'+text_remaining + '</span>');
});
});
Basically, what I think that it should happen is, that based on the areaid attr to also change the value of the span id="textarea_feedback" and textatea id="answer" to match the areaid value, so somehow the script would work separately to as many textareas I have.
Here is jsfiddle
Wrap that span and the textarea in an element like div so you can access both easily.
;window.onload = function(){
var text_max = 400;
for(var tL=document.querySelectorAll('.dummy textarea'), i=0, j=tL.length; i<j; i++){
$(tL[i]).on('input click keyup', function(){
var text_length = this.value.length;
var text_remaining = text_max - text_length;
this.parentNode.querySelector('span').textContent = text_remaining
})
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<div class = 'dummy'>
<span id="textarea_feedback1"></span>
<span> 🖊Characters left</span>
<br>
<textarea name="answer1" id="answer1" rows="4" placeholder="Type your answer here" areaid="1"></textarea>
</div>
<hr>
<div class = 'dummy'>
<span id="textarea_feedback2"></span>
<span> 🖊Characters left</span>
<br>
<textarea name="answer2" id="answer2" rows="4" placeholder="Type your answer here" areaid="2"></textarea>
</div>
</div>
You can also not rely on IDs at all, if you do it like this:
$(document).ready(function() {
var maxLen = 400,
$formGroup = $(".form-group"),
$addBtn = $("#add-textarea-btn");
$addBtn.click(createTextarea);
// Apply the function on pre-existing textareas
$("textarea", $formGroup).each(function(i, $el) {
updateCharCount.call($el);
});
// And whenever you edit one
$formGroup.on("input", "textarea", updateCharCount);
function createTextarea() {
$formGroup.append(
$(
"<hr />" +
'<span class="chars-left"></span><span> 🖊Characters left</span>' +
'<br /><textarea placeholder="Type your answer here"></textarea>'
)
);
updateCharCount.call($("textarea").last());
}
function updateCharCount() {
var $charLeft = $(this).prevAll(".chars-left").first(); // Get previous chars-left
$charLeft.text(maxLen - $(this).val().length);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="form-group">
<span class="chars-left"></span><span> 🖊Characters left</span>
<br />
<textarea placeholder="Type your answer here">There is some content already</textarea>
</div>
<button id="add-textarea-btn">New textarea</button>

Add bullet to multiple textarea and hidden textareas

I'm trying to add bullets to multiple textarea. This works fine when the textareas are not hidden, however I'd like to be able to add bullets to newly created textareas (click on the button "Add New". Ideally I'd like also newly created bullets to go to the next line rather than to be displayed side by side.
$(document).ready()
$('.add-bullet').click(function() {
$(this).parent().next('textarea').val(function(idx, value){
return value + '\u2022';
});
return false;
});
(function($) {
"use strict";
var itemTemplate = $('.workExperience-template').detach(),
editArea = $('.workExperience-area'),
itemNumber = 1;
$(document).on('click', '.workExperience-area .add', function(event) {
var item = itemTemplate.clone();
item.find('[name]').attr('name', function() {
return $(this).attr('name') + '_' + itemNumber;
});
++itemNumber;
item.prependTo(editArea);
});
$(document).on('click', '.workExperience-area .rem', function(event) {
editArea.children('.workExperience-template').last().remove();
});
$(document).on('click', '.workExperience-area .del', function(event) {
var target = $(event.target),
row = target.closest('.workExperience-template');
row.remove();
});
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="textarea">
<div>Add bullet</div>
<textarea id="todolist" class="todolist" name="todolist" placeholder="Write something.." ></textarea>
</div>
<div class="hidden">
<div class="workExperience-template">
<div class="textarea">
<div>Add bullet</div>
<textarea id="list" class="list" name="tata" placeholder="Write something.." ></textarea>
</div>
</div>
</div>
<div class="workExperience-area">
<button type="button" class="add buttonBlueAddField">Add New</button>
</div>
You should attach click event on newly created anchors:
$(document).ready()
$('.add-bullet').click(function() {
$(this).parent().next('textarea').val(function(idx, value){
return value + '\u2022';
});
return false;
});
(function($) {
"use strict";
var itemTemplate = $('.workExperience-template').detach(),
editArea = $('.workExperience-area'),
itemNumber = 1;
$(document).on('click', '.workExperience-area .add', function(event) {
var item = itemTemplate.clone();
item.find('[name]').attr('name', function() {
return $(this).attr('name') + '_' + itemNumber;
});
++itemNumber;
item.find(".add-bullet").click(function() {
$(this).parent().next('textarea').val(function(idx, value){
return value + '\u2022\n';
});
return false;
});
$(".textarea").next().append(item);
});
$(document).on('click', '.workExperience-area .rem', function(event) {
editArea.children('.workExperience-template').last().remove();
});
$(document).on('click', '.workExperience-area .del', function(event) {
var target = $(event.target),
row = target.closest('.workExperience-template');
row.remove();
});
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="textarea">
<div>Add bullet</div>
<textarea id="todolist" class="todolist" name="todolist" placeholder="Write something.." ></textarea>
</div>
<div class="hidden">
<div class="workExperience-template">
<div class="textarea">
<div>Add bullet</div>
<textarea id="list" class="list" name="tata" placeholder="Write something.." ></textarea>
</div>
</div>
</div>
<div class="workExperience-area">
<button type="button" class="add buttonBlueAddField">Add New</button>
</div>

How to cancel keypress in js?

I just started learning JavaScript. I have a question. When there are more than 160 characters, I do not want to type characters. How can I solve this problem?
<body> <textarea onkeypress="olay()" id="twitter" cols="30" rows="10"></textarea> <br>
<div id="sonuc"></div>
</body>
<script type="text/javascript">
i = 0;
function olay() {
i += 1;
if (i > 160) {
document.getElementById("sonuc").innerHTML = "Warning. Over 160 character";
document.getElementById("twitter").addEventListener("onkeypress", function(event)) {
event.preventDefault();
}
} else {
document.getElementById("sonuc").innerHTML = "Numver of charecter : " + i;
}
}
</script>
You don’t need JavaScript; text inputs have a maxlength attribute.
<textarea
onkeypress="olay()"
id="twitter"
cols="30"
rows="10"
maxlength="160"></textarea>
This is with html
<textarea
id="twitter"
cols="30"
rows="10"
maxlength="160"
placeholder="Enter text here...">
</textarea>
This how you would do it with JavaScript and HTML.
<body>
<textarea id="twitter" cols="30" rows="10" maxlength="160" placeholder="Enter text here..."></textarea><br>
<div id="sonuc"></div>
<script type="text/javascript">
function olay() {
var text = document.getElementById("twitter").innerHTML;
var i = text.length;
if (i >= 160) {
document.getElementById("sonuc").innerHTML = "Warning. Reached 160 character limit.";
}
else {
document.getElementById("sonuc").innerHTML = "Number of charecter : " + i;
}
}
document.addEventListener("keypress", function(){
olay();
});
document.addEventListener("keydown", function(){
olay();
});
</script>
</body>
the best you can do is write a regex and check every time on keypress.

How to count number of words in a textfield

I have a user enter biograpgy in a text box html for that is
<p>Biography:
<input type="text" id="biography" name="biography" />
<span id="biographyInvalid" style="color:red; visibility:hidden"> Biography is Invalid </span>
</p>
for Javascript i have a checkme function that is called and i want to do a check inside of it
function checkme(){
var biography=document.getElementById('biography').value;
}
how can i count number of words, do i first convert it to string and then separate with spaces
<div>
<div id="count">145</div>
<div id="barbox"><div id="bar"></div></div>
</div>
<textarea id="contentbox"></textarea>
and js
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#contentbox").keyup(function()
{
var box=$(this).val();
var main = box.length *100;
var value= (main / 145);
var count= 145 - box.length;
if(box.length <= 145)
{
$('#count').html(count);
$('#bar').animate(
{
"width": value+'%',
}, 1);
}
else
{
alert(' Full ');
}
return false;
});
});
</script>
$('#contentbox').keyup(function(){} - contentbox is the ID of the textbox.
Using $(this).val() getting the textbox value.
bar is the div ID of the count meter $('#bar').animate() increasing the width.
js:
$('#biography').keyup(function () {
var words = this.value.match(/\S+/g).length;
$('#count').html('Words Count:'+words);
});
HTML:
<div id="count"></div>
This gives you correct words count
This is working example
the HTML
<form name="myform" method="post" action="">
<textarea name="inpString" cols="80" rows="4" onkeyup="countNoOfWords()" >This is a sample text that has been typed to count the number of words it contains. Click the button below to find out.</textarea>
<br />
<input name="noofwords" type="text" value="" size="6" />
</form>
The JS function
<script type="text/javascript">
function countNoOfWords(){
document.myform.noofwords.value = document.myform.post_content.value.split(' ').length;
}
</script>
reference
$('input').keyup(function() {
var cs = this.value.match(/\S+/g).length;
$('#biography').text(cs);
});
Demo - http://jsfiddle.net/hNn5b/685/

Categories