textarea text erases when using innerHTML - javascript

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.

Related

Count character for textarea closest field

I have 4-5 textarea on my page and I have set the limitation of the character. The user can add 500 characters.
Now my issue is, I have to show the character count for the closest field. As of now, it's showing for all. I mean if I add any content in the first textarea then count showing for all textarea.
Please check the below image.
I was trying something like this
current = $(this).closest('.row .valInfo').find('.currentchar'),
maximum = $(this).closest('.valInfo').find('.maximumchar'),
//theCount = $('.valInfo');
theCount = $(this).closest('.valInfo')
$('.characterCount').keyup(function() {
var characterCount = $(this).val().length,
current = $('.currentchar'),
maximum = $('.maximumchar'),
theCount = $('.valInfo');
current.text(characterCount);
}
);
<div class="row">
<div class="col-lg-6">
<textarea maxlength="500" class="characterCount"></textarea>
<div class="valInfo"><span class="currentchar">0</span> <span class="maximumchar">/ 500</span> Characters</div>
</div>
<div class="col-lg-6">
<textarea maxlength="500" class="characterCount"></textarea>
<div class="valInfo"><span class="currentchar">0</span> <span class="maximumchar">/ 500</span> Characters</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
You want to find the corresponding currentchar, maximumchar and valinfo elements relative to the element that has been edited. For example by only finding matching elements in the shared parent:
$('.characterCount').keyup(function() {
var elem = $(this),
characterCount = elem.val().length;
current = elem.parent().find('.currentchar'),
maximum = elem.parent().find('.maximumchar'),
theCount = elem.parent().find('.valInfo');
current.text(characterCount);
}
);
<div class="row">
<div class="col-lg-6">
<textarea maxlength="500" class="characterCount"></textarea>
<div class="valInfo"><span class="currentchar">0</span> <span class="maximumchar">/ 500</span> Characters</div>
</div>
<div class="col-lg-6">
<textarea maxlength="500" class="characterCount"></textarea>
<div class="valInfo"><span class="currentchar">0</span> <span class="maximumchar">/ 500</span> Characters</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Make multiple additions with multiple input value Javascript

I am creating a lot of numbers inside of a div. Each time someone clicks a number I want to add it to another div. Let me make myself clear with some examples:
When a user clicks on the add class, the value of .addcop should be added to the value of .totalyHide. That means the value should change to 12.
When I click on the .add2 the value should be added on to 12, so the value of .totalyhide becomes 32.80.
and other terms, if I click the first + and click the second +, they should be added together on Yearly Price.
I hope you understand what I am trying to do.
$('.add').click(function() {
$('.addcop').click();
var dp = $(".addcop").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(dp);
$(".totaly").val("$" + bigTotal);
});
$('.add2').click(function() {
$('.procurement').click();
var procurement = $(".procurement").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(procurement);
$(".totaly").val("$" + bigTotal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<div class="box box6">
<div class="titlet">work on it
<hr>
</div>
<div class="explain">to help you better</div>
<div class="money">
<p class="me">$12 Yearly</p><i class="add fas fa-plus-square fa-2x"></i></div>
<input type="text" name="content" class="addcop" style="display: none;" value="12">
</div>
<div class="box box5">
<div class="titlet">Procurement
<hr>
</div>
<div class="explain"></div>
<div class="money">
<p class="me">$20.80 Yearly</p><i class="add2 fas fa-plus-square fa-2x"></i></div>
<input type="text" class="procurement" style="display: none;" value="20.80">
</div>
<div class="box box8">
<div class="total">Your First Deposit will be: <input class="total1" type="button" value="$546"></div>
<input type="text" class="totalHide" style="display: none;" value="546">
<div class="total">Yearly Price: <input onchange="myFunction()" class="totaly" type="button" value="$0"></div>
<input type="text" class="totalyHide" style="display: none;" value="0">
<div class="total">On-off Price: <input class="total" type="button" value="$546"></div>
<input type="text" class="total" style="display: none;" value="546">
</div>
There is a minor issue with the JQuery code that you have written. You can add the following changes to get the desired result.
$('.add').click(function() {
$('.addcop').click();
var dp = $(".addcop").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(dp);
$(".totalyHide").val(bigTotal); // Add this line here
$(".totaly").val("$" + bigTotal);
});
$('.add2').click(function() {
$('.procurement').click();
var procurement = $(".procurement").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(procurement);
$(".totalyHide").val(bigTotal); // Add this line here
$(".totaly").val("$" + bigTotal);
});
The thing to note here is that whenever you are calculating the total,
you'll have to set that total to $(".totalyHide"), so that you can read the updated value upon next click.

Display the form array inputs value before submitting the form

i have a single page which is divided into two sections.So at first first section is seen and we need to fill the inputs value and when we click go to next page button then the first section is now hidden and second section is shown.Then only we can submit the form.
Now what i want is that in the first section, i have four inputs like shown below
<div class="room_details_first col-md-12" id="first_order">
<div class="col-md-3">
<input type="text" placeholder="Food items" name="others_food_items[]" data-view-id="#location"/>
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel Name" name="others_hotel[]"/>
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel price" name="others_hotel_price[]"/>
</div>
<div class="col-md-3">
<input type="text" placeholder="Customer Price" name="others_client_price[]"/>
</div>
</div>
Now by using jquery i have append the inputs and the code is shown below
function add_others_order(){
var output="";
output+= '<div class="room_details_first col-md-12" id="first_order">';
output+='<div class="col-md-3"><input type="text" placeholder="Food items" name="others_food_items[]" data-view-id="#location"/></div>';
output+='<div class="col-md-3"> <input type="text" placeholder="Hotel Name" name="others_hotel[]"/> </div>';
output+='<div class="col-md-3"><input type="text" placeholder="Hotel price" name="others_hotel_price[]"/></div>';
output+='<div class="col-md-2"> <input type="text" placeholder="Customer Price" name="others_client_price[]"/></div>';
output+='<div class="col-md-1" ><i class="fa fa-remove"></i></div>';
output+='</div>';
$('#first_order').after(output);
}
now what i need is i need to save the inputs value before submitting and list it in second section of the page.i have tried to do it but i am failed many times. And i have also found similar answers which is given below
Display the data entered in a form before submitting the form
Guys i need help.
Here is what you want, you will get all input's value and you can do
what ever you want with it.
function nextStep() {
var allFields = document.getElementsByTagName("input");
//console.log(allFields);
for (var index in allFields) {
console.log('name : '+allFields[index].name);
if (allFields[index].type == "text") { // you can change condition by name instead of type
if (allFields.hasOwnProperty(index)) {
var attr = allFields[index];
console.log(attr.value)
}
}
}
}
<div class="col-md-3">
<input type="text" placeholder="Food items" name="others_food_items[]" data-view-id="#location" />
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel Name" name="others_hotel[]" />
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel price" name="others_hotel_price[]" />
</div>
<div class="col-md-3">
<input type="text" placeholder="Customer Price" name="others_client_price[]" />
</div>
<input type="button" onclick="nextStep()" value="Next step">
I think this is what you want, or as close to what you need, I add an Id attribute so you can do add/remove:
var stored_data = [];
stored_data.total = 0;
$('#dummy').on('click', function(){
var obj = {
id: stored_data.length,
food: food.value,
hotel_name: hotel_name.value,
hotel_price: hotel_price.value,
customer_price: customer_price.value
};
stored_data.push(obj);
stored_data.total += parseInt(obj.customer_price);
//$('#first_section').hide();
var output = '<div class="room_details_first col-md-12" id="first_order">';
output += '<div>Order ' + obj.id + '</div>';
output += '<div class="col-md-3">Food: ' + obj.food + '</div>';
output += '<div class="col-md-3">Hotel Name: ' + obj.hotel_name + '</div>';
output += '<div class="col-md-3">Hotel Price' + obj.hotel_price + '</div>';
output += '<div class="col-md-2">Customer Price' + obj.customer_price + '</div>';
output += '<div class="col-md-1" ><i class="fa fa-remove"></i></div>&nbsp';
$('#new_section').append(output);
$('#total').text(stored_data.total);
});
https://jsfiddle.net/5uka65tx/2/
Here's a way to do it by using clone() on the whole first order and do some modifications to add the link and change duplicate ID and last item column class.
First use serializeArray() to get the values to store
var values = $('#first_order :input').serializeArray();
console.log(values);
then clone , modify and insert
var link = '<div class="col-md-1" ><i class="fa fa-remove"></i>LINK</div>';
// clone first order and update ID
var $first = $('#first_order').clone().attr('id', 'first-order_2');
// modify column on last one and add the link
$first.children(':last').toggleClass('col-md-2 col-md-3').after(link);
// insert in second position
$('#second').append($first)
DEMO
By taking reference of Jigar7521, i tried to do the following way
var allFields = document.getElementsByClassName("others_order");
var others_total_price='0';
var others_food_items=new Array();
var others_hotel_name=new Array();
var others_hotel_price=new Array();
var others_client_price=new Array();
//var others['food_items'] = new Array();
var ficounter=0;
var hcounter=0;
var hpcounter=0;
var cpcounter=0;
Array.prototype.forEach.call(allFields, function(el) {
if(el.name=='others_client_price[]'){
others_client_price[cpcounter]=el.value;
cpcounter++;
others_total_price=parseFloat(others_total_price)+parseFloat(el.value);
}
if(el.name=='others_food_items[]'){
others_food_items[ficounter]=el.value;
ficounter++;
}
if(el.name=='others_hotel[]'){
others_hotel_name[hcounter]=el.value;
hcounter++;
}
if(el.name=='others_hotel_price[]'){
others_hotel_price[hpcounter]=el.value;
hcounter++;
}
});
$('#others_total_price').val(others_total_price);
var others_output="<h4>Others Order</h4>";
for(var i=0;i<=ficounter;i++){
others_output+='<div ><div class="col-md-12"><div class="col-md-3">'+others_food_items[i]+'</div><div class="col-md-3">'+others_hotel_name[i]+'</div><div class="col-md-3">'+others_hotel_price[i]+'</div><div class="col-md-3"> '+others_client_price[i]+'</div></div></div>';
}
$('#others_id').html(others_output);
it worked but i get errors like undefined
i tried to console.log every array and i got what i did not have expected

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

Create wysihtml5 dynamically

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

Categories