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>
Related
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++;
});
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>
How can I get the value of a textarea after input but not in same div with jQuery? I tried to do the foreach and find methods. I need to get the value and assign to JS object.
<div id="txtall">
<div class="subdiv">
<input type = "text" value = "firstInput" class= "subinput">
</div>
<textarea class="textarea" class="subTextarea"> firsttextareavalue </textarea>
<div class="subdiv">
<input type = "text" value = "secondInput" class= "subinput">
</div>
<textarea class="textarea" class="subTextarea" /></textarea>
<div class="subdiv">
<input type = "text" value = "thirdInput" class= "subinput">
</div>
<textarea class="textarea" class="subTextarea" />second may be empty</textarea>
<div class="subdiv">
<input type = "text" value = "forthInput" class= "subinput">
</div>
<textarea class="textarea" class="subTextarea" />last text area value</textarea>
When I click a button I need to get value.
$('#txtall').find('.subinput').each(function() {
console.log(this.value);
console.log($(".subtextarea",this).val());
});
The output needs to be:
firstInput
firsttextareavalue
secondInput
(this should be empty)
thirdInput
second may be empty
forthInput
last text area value
I also have to assign value to JS object.
function newObject(input,textarea)
{
this.input = input;
this.textarea = textarea;
}
var list = [];
$('#txtall').find('.subinput').each(function() {
var obj_1 = new newObject();
obj_1.input = this.value;
obj_1.textarea = $(".subtextarea",this).val();
list.push(obj_1);
});
By the way, I need to use this and I can't assign a different id or class to each input or textarea.
The textarea comes after the input, so it's the next() element from the parent .subdiv
$('#txtall').find('.subinput').each(function() {
console.log( this.value );
console.log( $(this).closest('.subdiv').next('.subtextarea').val() );
});
When you do $(".subtextarea",this) it's the same as $(this).find(".subtextarea"), which will only find descendants, and inputs don't have descendants.
Note that your HTML is invalid, you can only have the class attribute once, and you shouldn't be closing the textareas twice
There's also no reason to create instances here, and you can just map the elements
var list = $('#txtall').find('.subinput').map(function() {
return {
input : this.value,
textarea : $(this).closest('.subdiv').next('.subTextarea').val()
}
}).get();
console.log(list)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="txtall">
<div class="subdiv">
<input type="text" value="firstInput" class="subinput">
</div>
<textarea class="textarea subTextarea"> firsttextareavalue </textarea>
<div class="subdiv">
<input type="text" value="secondInput" class="subinput">
</div>
<textarea class="textarea subTextarea"></textarea>
<div class="subdiv">
<input type="text" value="thirdInput" class="subinput">
</div>
<textarea class="textarea subTextarea">second may be empty</textarea>
<div class="subdiv">
<input type="text" value="forthInput" class="subinput">
</div>
<textarea class="textarea subTextarea">last text area value</textarea>
</div>
Use .next() to get to the next element after the parent DIV.
function newObject(input, textarea) {
this.input = input;
this.textarea = textarea;
}
$("#button").click(function() {
var list = [];
$('#txtall').find('.subinput').each(function() {
var input = this.value;
var textarea = $(this).closest(".subdiv").next(".subTextarea").val();
var obj_1 = new newObject(input, textarea);
list.push(obj_1);
});
console.log(list);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="txtall">
<div class="subdiv">
<input type="text" value="firstInput" class="subinput">
</div>
<textarea class="subTextarea"> firsttextareavalue </textarea>
<div class="subdiv">
<input type="text" value="secondInput" class="subinput">
</div>
<textarea class="subTextarea" /></textarea>
<div class="subdiv">
<input type="text" value="thirdInput" class="subinput">
</div>
<textarea class="subTextarea" />second may be empty</textarea>
<div class="subdiv">
<input type="text" value="forthInput" class="subinput">
</div>
<textarea \class="subTextarea" />last text area value</textarea>
</div>
<button id="button">Click me</button>
$('#txtall').find('.subinput').each(function() {
console.log( this.value );
console.log( $(this).closest('.subdiv').next('textarea').val() );
});
Try this Code use $(this).parent().next().val(); it will get the textarea next to the parent of input.
function newObject(input,textarea)
{
this.input = input;
this.textarea = textarea;
}
var list = [];
$('#txtall').find('.subinput').each(function() {
var obj_1 = new newObject();
obj_1.input = this.value;
obj_1.textarea = $(this).parent().next().val();
list.push(obj_1);
});
Working Fiddle
Hi i´m trying to create multiple textareas with wysihtml5 0.3.0.
First generate HTML an then initialize the editors, I must customize blur for each textarea.
<div id="toolbar0" style="display: none;">
<a data-wysihtml5-command="bold" title="CTRL+B">bold</a> |
<a data-wysihtml5-command="italic" title="CTRL+I">italic</a>
<a data-wysihtml5-action="change_view">switch to html view</a>
</div>
<textarea id="textarea0" placeholder="Enter text ..."></textarea>
<br>
<br>
<div id="toolbar1" style="display: none;">
<a data-wysihtml5-command="bold" title="CTRL+B">bold</a> |
<a data-wysihtml5-command="italic" title="CTRL+I">italic</a>
<a data-wysihtml5-action="change_view">switch to html view</a>
</div>
<textarea id="textarea1" placeholder="Enter text ..."></textarea>
<br>
<br>
<div id="toolbar2" style="display: none;">
<a data-wysihtml5-command="bold" title="CTRL+B">bold</a> |
<a data-wysihtml5-command="italic" title="CTRL+I">italic</a>
<a data-wysihtml5-action="change_view">switch to html view</a>
</div>
<textarea id="textarea2" placeholder="Enter text ..."></textarea>
<script>
var editor = [];
var aux = [];
for(var i = 0; i <= 2; i++)
{
editor[i] = new wysihtml5.Editor("textarea" + i, {
toolbar: "toolbar" + i,
parserRules: wysihtml5ParserRules
});
aux[i] = editor[i].getValue();
var log = document.getElementById("log");
editor[i]
.on("blur", function() {
log.innerHTML += "<div>blur"+i+"</div><div>"+ aux[i] +"</div>";
})
}
</script>
Always in the blur event get the last textarea and undefined value:
blur3 undefined,blur3 undefined,blur3 undefined
Could someone help me out, thanks in advance.
You are into a function closure problem. When you define each onblur event, you tell Javascript to read the same i value for all of them (and in the end it becomes i=3).
Change it into this:
editor[i].on("blur", function(index) {
return function() { log.innerHTML += "<div>blur"+index+"</div><div>"+ aux[index] +"</div>"};
}(i));
I have two div called "answerdiv 1" & "answerdiv 2" in html.
now i want to give/create div id uniquely like "answerdiv 3" "answerdiv 4" "answerdiv 5" and so on.
Using javascript/jquery how can i append stuff in these dynamically created divs which id should be unique?
in my project user can add "n" numbers of div, there is no strict limit to it.
Help me out.
Thanks in Adv
================================================================================
My HTML code is:
<div id="answertextdiv">
<textarea id="answertext" name="answertext" placeholder="Type answer here" rows="2" cols="40" tabindex="6" onBlur="exchangeLabelsanswertxt(this);"></textarea>
</div>
My JS code:
function exchangeLabelsanswertxt(element)
{
var result = $(element).val();
if(result!="")
{
$(element).remove();
$("#answertextdiv").append("<label id='answertext' onClick='exchangeFieldanswertxt(this);'>"+result+"</label>");
}
}
function exchangeFieldanswertxt(element)
{
var result = element.innerHTML;
$(element).remove();
$("#answertextdiv").append("<textarea id='answertext' name='answertext' placeholder='Type answer here' rows='2' cols='40' tabindex='6' onBlur='exchangeLabelsanswertxt(this);'>"+result+"</textarea>");
}
Now from above code I want to append all stuff in unique "answertextdiv" id.
If your divs are in a container like:
<div id="container">
<div id="answerdiv 1"></div>
<div id="answerdiv 2"></div>
</div>
you could do something like:
//Call this whenever you need a new answerdiv added
var $container = $("container");
$container.append('<div id="answerdiv ' + $container.children().length + 1 + '"></div>');
If possible, try not to use global variables...they'll eventually come back to bite you and you don't really need a global variable in this case.
You can try something like this to create divs with unique ids.
HTML
<input type="button" value="Insert Div" onClick="insertDiv()" />
<div class="container">
<div id="answerdiv-1">This is div with id 1</div>
<div id="answerdiv-2">This is div with id 2</div>
</div>
JavaScript
var i=2;
function insertDiv(){
for(i;i<10;i++)
{
var d_id = i+1;
$( "<div id='answerdiv-"+d_id+"'>This is div with id "+d_id+"</div>" ).insertAfter( "#answerdiv-"+i );
}
}
Here is the DEMO
You should keep a "global" variable in Javascript, with the number of divs created, and each time you create divs you will increment that.
Example code:
<script type="text/javascript">
var divCount = 0;
function addDiv(parentElement, numberOfDivs) {
for(var i = 0; i < numberOfDivs; i++) {
var d = document.createElement("div");
d.setAttribute("id", "answerdiv"+divCount);
parentElement.appendChild(d);
divCount++;
}
}
</script>
And please keep in mind that jQuery is not necessary to do a lot of things in Javascript. It is just a library to help you "write less and do more".
I used below JQuery code for the same
$("#qnty1").on("input",function(e)
{
var qnt = $(this).val();
for (var i = 0; i < qnt; i++) {
var html = $('<div class="col-lg-6 p0 aemail1"style="margin-bottom:15px;"><input type="text" onkeyup= anyfun(this) class="" name="email1'+i+'" id="mail'+i+'" > </div><div id=" mail'+i+'" class="lft-pa img'+i+' mail'+i+'" > <img class="" src="img/btn.jpg" alt="Logo" > </div> <div id="emailer1'+i+'" class=" mailid "></div>');
var $html=$(html);
$html.attr('name', 'email'+i);
$('.email1').append($html);
}
}
my HTML contain text box like below.
<input type="text" name="qnty1" id="qnty1" class="" >
and
<div class="email1">
</div>
you need a global counter (more generally: a unique id generator) to produce the ids, either explicitly or implicitly (the latter eg. by selecting the last of the generated divs, identified by a class or their id prefix).
then try
var newdiv = null; // replace by div-generating code
$(newdiv).attr('id', 'answerdiv' + global_counter++);
$("#parent").append(newdiv); // or wherever
var newdivcount=0;
function insertDivs(){
newdivcount=newdivcount+1;
var id="answerdiv-"+(newdivcount);
var div=document.createElement("DIV");
div.setAttribute("ID",id);
var input=document.createElement("TEXTAREA");
div.appendChild(input);
document.getElementById('container').appendChild(input);
}
<button onclick="insertDivs">InsertDivs</button>
<br>
<div id="container">
<div id="answertextdiv">
<textarea id="answertext" name="answertext" placeholder="Type answer here" rows="2" cols="40" tabindex="6" onBlur="exchangeLabelsanswertxt(this);"></textarea>
</div>
</div>
Here is the another way you can try
// you can use dynamic Content
var dynamicContent = "Div NO ";
// no of div you want
var noOfdiv = 20;
for(var i = 1; i<=noOfdiv; i++){
$('.parent').append("<div class='newdiv"+i+"'>"+dynamicContent+i+"</div>" )
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
</div>