Create wysihtml5 dynamically - javascript

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));

Related

textarea text erases when using innerHTML

I have this function which uses innerHTML to insert html into a div:
function displayInputIntro() {
var submitbutton = document.getElementById('submitbutton')
var intro = document.getElementById('Intro')
var introNewSection = document.getElementById('intro-row')
var uniqueID = ""
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var length = 7
for (var i = length; i > 0; --i) uniqueID += chars[Math.floor(Math.random() * chars.length)];
uniqueID = uniqueID
introNewSection.innerHTML += '<div class="col-lg-5 mb-lg-0 mb-4" id=' + uniqueID + '><div class="card z-index-2"> <div class="card-body p-3" style="margin-top: -20px;"> <h6 class="ms-2 mt-4 mb-0">Intro <i class="fa fa-times" style="color: gray;"></i></h6> <p class="text-sm ms-2">Section 1</p> <div class="container border-radius-lg"> <div class="row"> <textarea type="text" class="form-control" name="intro" placeholder="Enter your current Intro" id="textvalue" style="height: 100px;" required></textarea> </div> </div> </div> </div></div>'
submitbutton.style.display = ''
}
and then my html:
<div class="row mt-4" id="intro-row"></div>
however, as you can see in the introNewSection.innerHTML, I have a <textarea type="text" class="form-control" name="intro" placeholder="Enter your current Intro" id="textvalue" style="height: 100px;" required></textarea>
the problem is, this function displayInputIntro() can be triggered multiple times. Every time its triggered, and there's any text inside the textarea, it just clears it and I don't know why. how can I fix this?
First thing you need to close the HTML tags properly, is not closing properly , i see is not having closing tag while assigning html to innerHTML, Second thing whenever you are using innerHTML it will override the html content.
If you want to inject the html then use insertAdjacentHTML tag and execute as below
introNewSection.insertAdjacentHTML('afterend', 'additional HTML code');
Note: You should find out why the function is triggering multiple times.

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>

select id that created dynamically in jquery

I wrote the below jQuery code, in this code when I click on #addbtn 2 text-box with this code below is created
var i = 2;
/* button #add_btn */
$(document).on("click", "#add_btn", function(evt) {
$('.add_checkbox').append("<input type='checkbox' id=foodcheckbox_" + i + " style='margin-bottom:20px;'><br/>");
$(".add_food").append("<input class='wide-control form-control default input-sm foodha' type='text' placeholder='Food' id=food_input" + i + " style='margin-bottom:5px;'>");
$(".add_price").append("<input class='wide-control form-control default input-sm priceha' type='text' placeholder='Price' id='price_input" + i + "' style='margin-bottom:5px;'>");
i++;
});
This code works fine, but when I want to select text-boxes that are added with the above code to get the content of them the selector by id isn't working, below is the code that I use to get value of these text-boxes:
/* button Submit */
$(document).on("click", ".uib_w_60", function(evt) {
var foodid = [];
var priceid = [];
/* your code goes here */
/* first I get id of .foodha class */
$(".foodha").each(function() {
var IDss = $(this).prop("id");
foodid.push(IDss);
});
/* second I get id of .priceha class */
$(".priceha").each(function() {
var pID = $(this).prop("id");
priceid.push(pID);
});
var newfoodpriceid = [];
/* here I dont know why the Id that gotten save
twice in array, for example save with this pattern
[food_input2, food_input3, food_input2, food_input3]
and to prevent this I use a trick and save it in another
array with the code below: */
for (var c = 0; c < priceid.length / 2; c++) {
newfoodpriceid.push({
'foodid': foodid[c],
'priceid': priceid[c]
});
}
/* then I want to get value of text box with exact
id that I select with jQuery selector but the
selector isn't working and the returned value
is nothing but I enter a value in text box that
have below id: */
var pr = $("#" + newfoodpriceid[0].priceid).val();
$("p").text(pr);
});
I explain anything that I think you need to know about what I want to do.
HTML code before I click on addbtn to add text-boxes:
<div class="grid grid-pad urow uib_row_42 row-height-42" data-uib="layout/row" data-ver="0">
<div class="col uib_col_46 col-0_1-12_1-7" data-uib="layout/col" data-ver="0">
<div class="widget-container content-area vertical-col center">
<div class="add_checkbox" style="margin-top:5px"></div>
<span class="uib_shim"></span>
</div>
</div>
<div class="col uib_col_48 col-0_6-12_6-7" data-uib="layout/col" data-ver="0">
<div class="widget-container content-area vertical-col">
<div class="add_food"></div>
<span class="uib_shim"></span>
</div>
</div>
<div class="col uib_col_47 col-0_5-12_5-5" data-uib="layout/col" data-ver="0">
<div class="widget-container content-area vertical-col">
<div class="add_price"></div>
<span class="uib_shim"></span>
</div>
</div>
<span class="uib_shim"></span>
</div>
And that HTML code after click on "add btn" twice
<div class="add_food">
<input class="wide-control form-control default input-sm foodha" type="text" placeholder="Food" id="food_input2" style="margin-bottom:5px;">
<input class="wide-control form-control default input-sm foodha" type="text" placeholder="Food" id="food_input3" style="margin-bottom:5px;">
</div>
<div class="add_price">
<input class="wide-control form-control default input-sm priceha" type="text" placeholder="Price" id="price_input2" style="margin-bottom:5px;">
<input class="wide-control form-control default input-sm priceha" type="text" placeholder="Price" id="price_input3" style="margin-bottom:5px;">
</div>
As you can see the text-box with the id that I want is generated fine, but I can't select it with using its id.
The only problem I see in your code is that once the page has run you must re-call the "each" function from jquery. When this "loop" is performed there are no "foodha" or "priceha" class cointaining elements. You could put the
$(".foodha").each(function() {
var IDss = $(this).prop("id");
foodid.push(IDss);
});
in a sleep loop or in a js function which you would call later.Like this:
setTimeout(function(){
$(".foodha").each(function() {
var IDss = $(this).prop("id");
foodid.push(IDss);
});
},1000); //for a second delay
or
function call_after_creating(){
$(".foodha").each(function() {
var IDss = $(this).prop("id");
foodid.push(IDss);
});
}

Show textarea or div (just below the comment to reply),when i click reply button on comment system javascript not jquery

So i am trying to make a comment system in my new site.All the comments have a reply button with id 'replybtn' which, onclick i want to show a textarea or input field inside a div with id 'replyform' right below the respective comment. And i am using php,mysql to retrieve comments.
<div class='cmt'>
<div class='cmttext'></div>
<div id='replybtn'></div>
<div id='replyform'>
<form method='post' ..... >
<textarea name='reply' ></textarea>
<input type='submit' />
</form>
</div>
</div>
Thank you. This is my first question asked on stackoverflow, so sorry if i have not given sufficient information.
Try this. It is plain JavaScript. Modify below what you want. :)
I updated it.
var varHtml = "<form method='post' ..... ><textarea name='reply' ></textarea> <input type='submit' /> </form>";
var allElements = document.body.getElementsByClassName("replybtn");
var addCommentField = function() {
for (var i = 0; allElements.length > i; i++) {
if (allElements[i] === this) {
console.log("this " + i);
if (document.getElementsByClassName("replyform")[i].innerHTML.length === 0) {
document.getElementsByClassName("replyform")[i].innerHTML = varHtml;
}
}
}
};
for (var i = 0; i < allElements.length; i++) {
allElements[i].addEventListener('click', addCommentField, false);
}
<div class='cmt'>
<div class='cmttext'></div>
<button class='replybtn'>replybtn</button>
<div class='replyform'></div>
</div>
<div class='cmt'>
<div class='cmttext'></div>
<button class='replybtn'>replybtn</button>
<div class='replyform'></div>
</div>
<div class='cmt'>
<div class='cmttext'></div>
<button class='replybtn'>replybtn</button>
<div class='replyform'></div>
</div>

Livequery and each()

i have an .each() loop doing something on all matching elements. but i also have a way to add those elements.... i'm trying to get livequery to realize that a new element has been added and run it through the same each loop.
here's a general setup:
http://jsfiddle.net/CUURF/1/
basically, how do i use livequery and each together?
ultimately it is so that i can dynamically add tinymce editor textboxes in metaboxes, but i am fairly certain the problem is that my IDs aren't autoincremting on the add/clone, since the new element isn't in the DOM for the each loop.
edit- i think the biggest thing is that i need the index counter that comes standard w/ .each to work w/ livequery?
edit- here's the code from wpalchemy for looping/cloning
/* <![CDATA[ */
jQuery(function($)
{
$(document).click(function(e)
{
var elem = $(e.target);
if (elem.attr('class') && elem.filter('[class*=dodelete]').length)
{
e.preventDefault();
var p = elem.parents('.postbox'); /*wp*/
var the_name = elem.attr('class').match(/dodelete-([a-zA-Z0-9_-]*)/i);
the_name = (the_name && the_name[1]) ? the_name[1] : null ;
/* todo: expose and allow editing of this message */
if (confirm('This action can not be undone, are you sure?'))
{
if (the_name)
{
$('.wpa_group-'+ the_name, p).not('.tocopy').remove();
}
else
{
elem.parents('.wpa_group').remove();
}
the_name = elem.parents('.wpa_group').attr('class').match(/wpa_group-([a-zA-Z0-9_-]*)/i)[1];
checkLoopLimit(the_name);
$.wpalchemy.trigger('wpa_delete');
}
}
});
$('[class*=docopy-]').click(function(e)
{
e.preventDefault();
var p = $(this).parents('.postbox'); /*wp*/
var the_name = $(this).attr('class').match(/docopy-([a-zA-Z0-9_-]*)/i)[1];
var the_group = $('.wpa_group-'+ the_name +':first.tocopy', p);
var the_clone = the_group.clone().removeClass('tocopy');
var the_props = ['name', 'id', 'for'];
the_group.find('input, textarea, select, button, label').each(function(i,elem)
{
for (var j = 0; j < the_props.length; j++)
{
var the_prop = $(elem).attr(the_props[j]);
if (the_prop)
{
var the_match = the_prop.match(/\[(\d+)\]/i);
if (the_match)
{
the_prop = the_prop.replace(the_match[0],'['+(+the_match[1]+1)+']');
$(elem).attr(the_props[j], the_prop);
}
}
}
});
if ($(this).hasClass('ontop'))
{
$('.wpa_group-'+ the_name +':first', p).before(the_clone);
}
else
{
the_group.before(the_clone);
}
checkLoopLimit(the_name);
$.wpalchemy.trigger('wpa_copy', [the_clone]);
});
function checkLoopLimit(name)
{
var elem = $('.docopy-' + name);
var the_match = $('.wpa_loop-' + name).attr('class').match(/wpa_loop_limit-([0-9]*)/i);
if (the_match)
{
var the_limit = the_match[1];
if ($('.wpa_group-' + name).not('.wpa_group.tocopy').length >= the_limit)
{
elem.hide();
}
else
{
elem.show();
}
}
}
/* do an initial limit check, show or hide buttons */
$('[class*=docopy-]').each(function()
{
var the_name = $(this).attr('class').match(/docopy-([a-zA-Z0-9_-]*)/i)[1];
checkLoopLimit(the_name);
});
});
/* ]]> */
</script>
and the markup for inside my metabox:
<div id="testimonials">
<h2>Testimonials</h2>
<a style="float:right; margin:0 10px;" href="#" class="dodelete-testimonials button"><span class="icon delete"></span>Remove All</a>
<div id="wpa_loop-testimonials" class="wpa_loop wpa_loop-testimonials"><div class="wpa_group wpa_group-testimonials first">
<span class="icon delete"></span>Remove
<div class="slide_preview">
<div class="preview_wrap">
<img class="preview" src="" alt="preview" />
</div>
<input type="hidden" name="_sidebar_meta[testimonials][0][testimonial_image]" value="" class="img_src" />
<input type="hidden" name="_sidebar_meta[testimonials][0][slide_image_alt]" value="" class="img_alt" />
<button class="upload_image_button button" type="button"><span class="icon upload"></span>Change Photo</button>
</div>
<div class="slide_text">
<label>About Testimonial</label>
<div class="customEditor minimal">
<textarea rows="5" cols="50" name="_sidebar_meta[testimonials][0][testimonial_desc]">I realized it was ME causing all the problems</textarea>
</div>
</div>
</div> <div class="wpa_group wpa_group-testimonials last tocopy">
<h3 class="slide">Testimonial Name:
<input type="text" name="_sidebar_meta[testimonials][1][testimonial_name]" value="" />
</h3>
<span class="icon delete"></span>Remove
<div class="slide_preview">
<div class="preview_wrap">
<img class="preview" src="http://localhost/multi/wp-content/themes/callingintheone/functions/WPAlchemy/images/default_preview.png" alt="_sidebar_meta[testimonials][1][testimonial_image] Preview" />
</div>
<input type="hidden" name="_sidebar_meta[testimonials][1][testimonial_image]" value="" class="img_src" />
<input type="hidden" name="_sidebar_meta[testimonials][1][slide_image_alt]" value="" class="img_alt" />
<button class="upload_image_button button" type="button"><span class="icon upload"></span>Upload Photo</button>
</div>
<div class="slide_text">
<label>About Testimonial</label>
<div class="customEditor minimal">
<textarea rows="5" cols="50" name="_sidebar_meta[testimonials][1][testimonial_desc]"></textarea>
</div>
</div>
</div></div>
<p style="margin-bottom:15px; padding-top:5px;"><span class="icon add"></span>Add Testimonial</p>
</div>
the .tocopy class gets shifted by the alchemy code to a new hidden (by CSS) and last element
Your problem was that each was not executing with the clik. And after that there was nothing to make it run.
fixed code
Answer: http://jsfiddle.net/morrison/CUURF/6/
Notes:
Does not use livequery. There's no need to in this instance.
Keeps track of existing editors in an array. This is faster than cycling through the DOM every time you want an editor. DOM stuff is slow, arrays are fast. This also gives you easy access to any or all of the editors for other things you might do.
Doesn't cycle when a new editor is created. It simply modifies the new editor to have an id of the last one plus 1. This is a huge performance boost.

Categories