Changing a div's output based off of another div's price - javascript

I have a page with some billing info. I want to affect a div based on the values of other divs. But, there is no output in my desired div.
Below is what I have so far:
$(document).ready(function () {
$(".content-wrapper.planwrapper").each(function() {
var originalRate = $(this).find(".v-ratePlanValue").text().replace("¢","");
var newBill = eval(originalRate*500+5.95);
});
$(this).find(".estimatedbill-wrapper .term-description").replace($(this),'$newBill');
});
I'm pretty new to JS, so any help would be appreciated!
Edit: Here is the HTML for one of the divs I'm working with -
<div class="esco_electric">
<div class="esco_lower-wrapper">
<div class="esco_rates-list" id="electric_list">
<div class="rate-item row-id-Electric-' . $oneplan->ProductId . '-' . $oneplan->UtilityID . ' color3" data-product-id="' . $oneplan->ProductId . '" data-utility-id="' . $oneplan->UtilityID . '" data-tpv-id="' . $oneplan->TPVTemplateID . '" data-utility-name="' . $oneplan->UtilityShortName . '" data-zone="">
<!-- Price / Suffix / Plan Type -->
<div class="rate-type rate-wrapper">
<div class="rate-price" style="position:relative;">
<div class="mobleft" style="margin-bottom: 0px;">Fixed Rate</div>
<div id="pricediv-Electric-1853-50" class="price v-ratePlanValue mobcenter" style="padding-top:5px;">7.4<span style="font-size:0.7em;">¢</span></div>
<div class="price-suffix v-rateMeasurementSuffix mobright">kWh </div>
</div>
</div>
<!-- Description Area -->
<div class="rate-description description-wrapper">
<!-- Upper Description -->
<div class="description-text">
<div class="term-title">Term</div>
<div class="term-description">
6 Months </div>
<div class="description-contentpricediv-Electric-1853-50 v-ratePlanDescription">No Cancellation Fee </div>
</div>
</div>
<div class="rate-description estimatedbill-wrapper">
<div class="description-text">
<div class="estimatedbill-title">Estimated Bill</div>
<div class="term-description">
$148 </div>
<div class="v-ratePlanDescription howisthiscalculated" data-mfp-src="#howisthiscalculated-popover">
How is this calculated?
</div>
</div>
</div>
<style>
.description-contentpricediv-Electric-1853-50 {
margin-top: 19px;
text-align: center;
font-size: 16px !important;
color: #535353!important;
}
</style>
<!-- Action buttons -->
<a id="selectrateid-Electric-1853-50" href="index.php?type=resi&s=options_and_information&plan=1853&StartDate=12-May-2016">
<div class="selectplan">
<p>Select Plan</p>
</div>
</a>
<a class="rate-edit" href="#">
<img src="images/check.png">
<p>
Edit Plan
</p>
</a>
</div>
<!-- end rateitem -->
<div id="UDSDIVID-Electric-1853-50" data-alert="" class="alert-box radius infodiv">
<div class="pdfdiv">
<a eslinktext="Datos de la Electricidad" eslinkurl="PDFTemplates/ResidentialContracts/EFLViewer.php?lang=es&key=RW5lcmd5Q2hhcmdlPTQuMSZQbGFuTmFtZT1UaGluayBTZWN1cmUgNiZJc3N1ZURhdGU9MDUvMTIvMjAxNiZVdGlsaXR5U2hvcnROYW1lPU9OQ09SJnByb2R1Y3R0ZXJtPTYmdGVybWZlZT0w" class="pdfcustom" href="PDFTemplates/ResidentialContracts/EFLViewer.php?key=RW5lcmd5Q2hhcmdlPTQuMSZQbGFuTmFtZT1UaGluayBTZWN1cmUgNiZJc3N1ZURhdGU9MDUvMTIvMjAxNiZVdGlsaXR5U2hvcnROYW1lPU9OQ09SJnByb2R1Y3R0ZXJtPTYmdGVybWZlZT0w" target="_blank" style="color:#000000;"><img src="images/pdf.png" height="25" width="25"> Electricity Facts Label</a><br>
<a eslinktext="Terminos y Condiciones" eslinkurl="PDFTemplates/TermsofServices/TOS_TX_Spanish.pdf?key=c3RhdGU9VFgmcmF0ZT00LjEmdGVybT02JnBsYW5uYW1lPVRoaW5rIFNlY3VyZSA2" class="pdfcustom" href="PDFTemplates/contract_api/index.php/contract/TC/state/TX/customer_type/RESI/service/Electric?PlanName=Think+Secure+6&ContractNumber=TBD&ServiceAddress=&Price=4.1&ServiceCity=&ServiceAddress2=&ServiceState=&ServiceZipCode=&Term=6&MonthEnding=November&Timestamp=1463061182 " target="_blank" style="color:#000000;"><img src="images/pdf.png" height="25" width="25"> Terms of Service</a><br>
<a eslinktext="Sus Derechos como Cliente" eslinkurl="PDFTemplates/Contracts/TX_YRAC_Spanish.pdf" class="pdfcustom" href="PDFTemplates/Contracts/TX_YRAC.pdf" target="_blank" style="color:#000000;"><img src="images/pdf.png" height="25" width="25"> Your Rights as a Customer</a><br><br>
</div>
<!-- end pdfdiv-->
<div class="textrightdiv">Please contact Customer Care to request that a written copy of the terms of service document be sent to you by regular U.S. mail.<br><br><span style="padding-right: 30px;">Email Request: </span>customercare#mythinkenergy.com<br><span style="padding-right: 25px;">Phone Request: </span>1-888-238-5610<br><a class="small button spanishButton" name="btnshowspanish" id="btnshowspanish22422" onclick="showspanishcontracts('btnshowspanish22422');">Documentos en Español</a></div><a onclick="$('#UDSDIVID-Electric-1853-50').hide();" style="display: none; padding: 10px;color:#000000;cursor: pointer; cursor: hand;position: absolute;top: 10px; right: 10px;">X</a>
<div style="clear: both;"></div>
</div>
</div>
</div>
</div>

Your logic is correct, while your code is incorrect, there are several mistakes that needs to be fixed:
There's no need to use eval, it has no effect in your code and it's better to avoid its use.
To use the variable newBill you don't need to write $newBill and
if you put it inside '' it will be interpreted as string and simply printthe sentence$newBill`.
And in your case you declared the variable newBill inside .each function so it will be undefined outside this function scope so you can't use it outside of it, you need to declare it outside it.
And the use of $(".content-wrapper.planwrapper").each(function() { is unnecessary in your case and will break your code.
And You are using .replace() in the wrong place, to change the
content of a div use .text(content) and not .replace().
This is how should be your code:
$(document).ready(function() {
var newBill = 0;
var originalRate = $(this).find(".v-ratePlanValue").text().replace("¢", "");
newBill = parseFloat(originalRate) * 500 + 5.95;
$(this).find(".estimatedbill-wrapper .term-description").text(newBill);
});
THis is a working DEMO:
$(document).ready(function() {
var newBill = 0;
var originalRate = $(this).find(".v-ratePlanValue").text().replace("¢", "");
newBill = parseFloat(originalRate) * 500 + 5.95;
$(this).find(".estimatedbill-wrapper .term-description").text(newBill);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="esco_electric
">
<div class="esco_lower-wrapper">
<div class="esco_rates-list" id="electric_list">
<div class="rate-item row-id-Electric-' . $oneplan->ProductId . '-' . $oneplan->UtilityID . ' color3" data-product-id="' . $oneplan->ProductId . '" data-utility-id="' . $oneplan->UtilityID . '" data-tpv-id="' . $oneplan->TPVTemplateID . '" data-utility-name="' . $oneplan->UtilityShortName . '"
data-zone="">
<!-- Price / Suffix / Plan Type -->
<div class="rate-type rate-wrapper">
<div class="rate-price" style="position:relative;">
<div class="mobleft" style="margin-bottom: 0px;">Fixed Rate</div>
<div id="pricediv-Electric-1853-50" class="price v-ratePlanValue mobcenter" style="padding-top:5px;">7.4<span style="font-size:0.7em;">¢</span>
</div>
<div class="price-suffix v-rateMeasurementSuffix mobright">
kWh</div>
</div>
</div>
<!-- Description Area -->
<div class="rate-description description-wrapper">
<!-- Upper Description -->
<div class="description-text">
<div class="term-title">Term</div>
<div class="term-description">
6 Months</div>
<div class="description-contentpricediv-Electric-1853-50 v-ratePlanDescription">
No Cancellation Fee</div>
</div>
</div>
<div class="rate-description estimatedbill-wrapper">
<div class="description-text">
<div class="estimatedbill-title">Estimated Bill</div>
<div class="term-description">
$148</div>
<div class="v-ratePlanDescription howisthiscalculated" data-mfp-src="#howisthiscalculated-popover">
How is this calculated?
</div>
</div>
</div>
<style>
.description-contentpricediv-Electric-1853-50 {
margin-top: 19px;
text-align: center;
font-size: 16px !important;
color: #535353!important;
}
</style>
<!-- Action buttons -->
<a id="selectrateid-Electric-1853-50" href="index.php?type=resi&s=options_and_information&plan=1853&StartDate=12-May-2016">
<div class="selectplan">
<p>Select Plan</p>
</div>
</a>
<a class="rate-edit" href="#">
<img src="images/check.png">
<p>
Edit Plan
</p>
</a>
</div>
<!-- end rateitem -->
<div id="UDSDIVID-Electric-1853-50" data-alert="" class="alert-box radius infodiv">
<div class="pdfdiv">
<a eslinktext="Datos de la Electricidad" eslinkurl="PDFTemplates/ResidentialContracts/EFLViewer.php?lang=es&key=RW5lcmd5Q2hhcmdlPTQuMSZQbGFuTmFtZT1UaGluayBTZWN1cmUgNiZJc3N1ZURhdGU9MDUvMTIvMjAxNiZVdGlsaXR5U2hvcnROYW1lPU9OQ09SJnByb2R1Y3R0ZXJtPTYmdGVybWZlZT0w"
class="pdfcustom" href="PDFTemplates/ResidentialContracts/EFLViewer.php?key=RW5lcmd5Q2hhcmdlPTQuMSZQbGFuTmFtZT1UaGluayBTZWN1cmUgNiZJc3N1ZURhdGU9MDUvMTIvMjAxNiZVdGlsaXR5U2hvcnROYW1lPU9OQ09SJnByb2R1Y3R0ZXJtPTYmdGVybWZlZT0w" target="_blank" style="color:#000000;">
<img src="images/pdf.png" height="25" width="25">Electricity Facts Label</a>
<br>
<a eslinktext="Terminos y Condiciones" eslinkurl="PDFTemplates/TermsofServices/TOS_TX_Spanish.pdf?key=c3RhdGU9VFgmcmF0ZT00LjEmdGVybT02JnBsYW5uYW1lPVRoaW5rIFNlY3VyZSA2" class="pdfcustom" href="PDFTemplates/contract_api/index.php/contract/TC/state/TX/customer_type/RESI/service/Electric?PlanName=Think+Secure+6&ContractNumber=TBD&ServiceAddress=&Price=4.1&ServiceCity=&ServiceAddress2=&ServiceState=&ServiceZipCode=&Term=6&MonthEnding=November&Timestamp=1463061182 "
target="_blank" style="color:#000000;">
<img src="images/pdf.png" height="25" width="25">Terms of Service</a>
<br>
<a eslinktext="Sus Derechos como Cliente" eslinkurl="PDFTemplates/Contracts/TX_YRAC_Spanish.pdf" class="pdfcustom" href="PDFTemplates/Contracts/TX_YRAC.pdf" target="_blank" style="color:#000000;">
<img src="images/pdf.png" height="25" width="25">Your Rights as a Customer</a>
<br>
<br>
</div>
<!-- end pdfdiv-->
<div class="textrightdiv">Please contact Customer Care to request that a written copy of the terms of service document be sent to you by regular U.S. mail.
<br>
<br><span style="padding-right: 30px;">Email Request: </span>customercare#mythinkenergy.com
<br><span style="padding-right: 25px;">Phone Request: </span>1-888-238-5610
<br><a class="small button spanishButton" name="btnshowspanish" id="btnshowspanish22422" onclick="showspanishcontracts('btnshowspanish22422');">Documentos en Español</a>
</div><a onclick="$('#UDSDIVID-Electric-1853-50').hide();" style="display: none; padding: 10px;color:#000000;cursor: pointer; cursor: hand;position: absolute;top: 10px; right: 10px;">X</a>
<div style="clear: both;"></div>
</div>
</div>
</div>
</div>

Check it out: https://jsfiddle.net/vmtzqnu0/5/
There are a few things to fix to get this working:
1. Your use of var
This keyword creates a variable within the code block (scope) that you use it, but outside of that block it's no longer usable. So when you say var newBill = ... inside the $.each() loop, you can't use it outside of there.
We can fix this by removing the keyword and (optionally) add the var newBill; statement just outside that block:
$(document).ready(function () {
var newBill; // will be used later
$(".content-wrapper.planwrapper").each(function() {
var originalRate = $(this).find(".v-ratePlanValue").text().replace("¢","");
newBill = eval(originalRate*500+5.95);
});
$(this).find(".estimatedbill-wrapper .term-description").replace($(this),'$newBill');
});
2. Your use of eval()
You should probably just never use eval(). Moreover, it doesn't do what you think. You pass it a string of JS code and it will run that code. You don't pass it a statement.
So newBill = eval(originalRate*500+5.95); becomes newBill = originalRate*500+5.95;. You're best off wrapping that in parseFloat() too:
newBill = parseFloat(originalRate) * 500 + 5.95;
3. Your use of $.replace()
Here you actually want to use $.text() or $.html(). These functions are used to replace the content of an element. So, your final code will look like this:
$(document).ready(function() {
var newBill;
$(".content-wrapper.planwrapper").each(function() {
var originalRate = $(this).find(".v-ratePlanValue").text().replace("¢", "");
newBill = parseFloat(originalRate) * 500 + 5.95;
});
$(this).find(".estimatedbill-wrapper .term-description").text(newBill)
});
4. There is no .planwrapper
Instead, loop through .v-ratePlanValue:
$(document).ready(function() {
var newBill;
$(".v-ratePlanValue").each(function() {
var originalRate = $(this).text().replace("¢", "");
console.log(this, originalRate);
newBill = '$' + ((parseFloat(originalRate) * 500) + 5.95);
});
$(this).find(".estimatedbill-wrapper .term-description").text(newBill)
});
Good resources while learning Javascript, jQuery:
MDN JS Tutorial
jQuery Documentation
JS Debugging Guide

Related

Putting if and else in Foreach loop in ASP.NET MVC C#

When I wrote the if and else statement in a foreach loop, I have encountered an error. I'm not sure what went wrong. I even added #if and #var{ }; to the code. But there is still error.
It's not a good idea to mix partial html fragments with conditional C#/Razor code. The code might repeat but it's far easier to read and maintain later.
I may not have captured your intent correctly, but I can read this and understand how the condition affects the output.
#foreach (var item in Model)
{
var HeaderImage = item.HeaderPath;
if (image != "")
{
var fileSavePath = Path.Combine(#"\\mainPage.com", "");
<div class="picGallery">
<img src="#Url.Content(item.HeaderPath)" alt="Image" />
<a href="#Url.Action("ViewPage", "Home")">
</a>
<div class="desc2">
<p style="font-size: 13;">#item.Text</p>
<p style="font-size: 13;">#item.text_2</p>
</div>
</div>
}
else
{
<div class="picGallery">
<img src="#Url.Content(item.HeaderPath)" alt="Image" />
<a href="#Url.Action("ViewPage", "Home")">
<div id="scanIcon">
<img src=img.png alt="imageView" />
<h1 style="font-size: 10px;">View Image</h1>
</div>
</a>
<div class="desc2">
<p style="font-size: 13;">#item.Text</p>
<p style="font-size: 13;">#item.text_2</p>
</div>
</div>
}
}
You can shorten this. But you need to be careful to escape the #if the nested blocks of code within html. It also becomes more difficult to understand what the output should be.
#foreach (var item in Model)
{
var HeaderImage = item.HeaderPath;
<div class="picGallery">
<img src="#Url.Content(item.HeaderPath)" alt="Image" />
<a href="#Url.Action("ViewPage", "Home")">
#if (image != "")
{
// image exists
var fileSavePath = Path.Combine(#"\\mainPage.com", "");
<div> </div>
}
else
{
<div id="scanIcon">
<img src=img.png alt="imageView" />
<h1 style="font-size: 10px;">View Image</h1>
</div>
}
</a>
<div class="desc2">
<p style="font-size: 13;">#item.Text</p>
</div>
</div>
}

Javascript - constructor cannot be called as a function

Please, could you tell me what's wrong in this code ?
This is Django framework + JS.
I want to make my div block to be visible when I click on the button.
Everything else is working fine. I mean my loop is ok and comment.id returns a unique ID.
When I click on the button, I have a JS error: "constructor cannot be called as a function"
Uncaught TypeError: Failed to construct 'Comment': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
at HTMLButtonElement.onclick ((index):218)
onclick # (index):218
(index):218 Uncaught TypeError: Failed to construct 'Comment': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
at HTMLButtonElement.onclick ((index):218)
onclick # (index):218
My code:
<!-- Button see comments -->
<button
onclick="Comment()"
type="button"
class="w3-button w3-theme-d1 w3-margin-bottom">
Commenter
</button>
<!-- end button -->
{%for comment in comments%}
{%if comment.articles.id == post.id or comment.statut.id == post.id %}
<!-- Bloc comments-->
<div id="{{comment.id}}" style="overflow-wrap: break-word; display: none;" class="w3-container w3-card-2 w3-white w3-round w3-margin">
<p>{{comment.text}}</p>
<p style="width: 100%; text-align: right;">
<img alt="Avatar" class="w3-circle-articles" style="vertical-align:middle;" src="{{media}}{{comment.author.profile.avatar}}" />
<span style="color: #0477BF;"">{{comment.author}}</span> le {{comment.date|date:"d F"}} à {{comment.date|date:"H:m"}}
</p>
</div>
<!-- End bloc comments -->
<!-- JAVASCRIPT to see comments -->
<script type="text/javascript">
function Comment{{comment.id}}() {
document.getElementById("{{comment.id}}").style.display = "block";
}
</script>
<!-- End JAVASCRIPT -->
{%endif%}
{%endfor%}
This is what it looks like in HTML when I look at the source code of the page:
<div id="2" style="overflow-wrap: break-word; display: ;" class="w3-container w3-card-2 w3-white w3-round w3-margin">
<p>lol</p>
<p style="width: 100%; text-align: right;">
<img alt="Avatar" class="w3-circle-articles" style="vertical-align:middle;" src="http://******/media/user/user_20/avatar/horror-gaming-avatar.png">
<span style="color: #0477BF;" "="">Preyor</span> le 10 juillet à 10:07
</p>
</div>
<script type="text/javascript">
function Comment2() {
document.getElementById("2").style.display = "block";
}
i = i+1
document.getElementById("Comment_Count3").innerHTML = i;
</script>
<div id="3" style="overflow-wrap: break-word; display: ;" class="w3-container w3-card-2 w3-white w3-round w3-margin">
<p>hihi</p>
<p style="width: 100%; text-align: right;">
<img alt="Avatar" class="w3-circle-articles" style="vertical-align:middle;" src="http://*********/media/user/user_4/avatar/hebus_1920x1080_1464110916_5053_sMlLt6u.jpg">
<span style="color: #0477BF;" "="">GrandGTO</span> le 18 juillet à 02:07
</p>
</div>
<script type="text/javascript">
function Comment3() {
document.getElementById("3").style.display = "block";
}
i = i+1
document.getElementById("Comment_Count3").innerHTML = i;
</script>
The problem is that the Comment() function is not defined. Javascript Engine is not able to find definition of Comment().There is definitions for Comment2(), Comment3(). But no definition for Comment().
function Comment{{comment.id}}() { // it should be Comment and not Comment{{comment.id}}
document.getElementById("{{comment.id}}").style.display = "block";
}

Is it possible to remove size from the end a responsive image path?

I want to remove the -500x500 part from the image so that I can show the actual image.
Here's the complete HTML if anybody wants to take a look:
<div id="speakers_list1" class="wpb_row vc_row mk-fullwidth-false attched-false vc_row-fluid js-master-row mk-in-viewport">
<div style="" class="vc_col-sm-12 wpb_column column_container _ height-full">
<div id="box-14" class="mk-employees a_margin-bottom-10 a_margin-top-10 four-column u6col u5col o0col o1col o2col o3col mk-employees-grayscale classic c_cs ">
<ul>
<li class="mk-employee-item a_colitem a_align-center a_display-inline-block a_float-left m_7">
<div class="item-holder">
<div class="team-thumbnail a_position-relative a_width-100-per a_height-100-per a_overflow-hidden rounded-true">
<a href="http://developer.designprowebsolutions.com/sufi-intensive/team/imam-abdoulaye-ndaw/">
<img alt="Imam Abdoulaye Ndaw" title="Imam Abdoulaye Ndaw" src="http://developer.designprowebsolutions.com/sufi-intensive/wp-content/uploads/2017/02/imam-abdoulahy-ndaw-500x500.jpg">
</a>
<div class="employee-hover-overlay a_m_fly-top-left a_opacity-100 "></div>
</div>
<div class="team-info-wrapper m_7" itemscope="itemscope" itemtype="https://schema.org/Person">
<a class="team-member-name" href="http://developer.designprowebsolutions.com/sufi-intensive/team/imam-abdoulaye-ndaw/">
<span class="team-member-name a_font-16 a_display-block a_font-weight-bold a_text-transform-up a_color-333">Imam Abdoulaye Ndaw</span>
</a>
<span class="team-member-position a_font-12 a_text-transform-up a_display-block a_color-777 a_letter-spacing-1">Imam & Ustadz</span>
<div class="team-member-desc a_margin-top-20 a_margin-bottom-10 a_display-block"></div>
</div>
</div>
A quick way(not beautiful) is to replace the src of the element
src is a attribute on the element, so you can get the value with $(obj).attr("src") or set the value with $(obj).attr("src","newValue")
Edit I created a function so you can do this multiple times with multiple objects
Either add a class to the img, you want to change or call it by an attribute.
Class: fixImage($('.removeRatio'), "-500x500") or
Attribute: fixImage($('[title="Imam Abdoulaye Ndaw"]'), "-500x500")
console.log("This was my SRC: " + $('.removeRatio').attr("src"))
function fixImage(obj, removestring)
{
obj.attr("src", obj.attr("src").replace(removestring, ""))
}
fixImage($('.removeRatio'), "-500x500")
console.log("This now IS my SRC: " + $('.removeRatio').attr("src"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="speakers_list1" class="wpb_row vc_row mk-fullwidth-false attched-false vc_row-fluid js-master-row mk-in-viewport">
<div style="" class="vc_col-sm-12 wpb_column column_container _ height-full">
<div id="box-14" class="mk-employees a_margin-bottom-10 a_margin-top-10 four-column u6col u5col o0col o1col o2col o3col mk-employees-grayscale classic c_cs ">
<ul>
<li class="mk-employee-item a_colitem a_align-center a_display-inline-block a_float-left m_7">
<div class="item-holder">
<div class="team-thumbnail a_position-relative a_width-100-per a_height-100-per a_overflow-hidden rounded-true">
<a href="http://developer.designprowebsolutions.com/sufi-intensive/team/imam-abdoulaye-ndaw/">
<img class="removeRatio" alt="Imam Abdoulaye Ndaw" title="Imam Abdoulaye Ndaw" src="http://developer.designprowebsolutions.com/sufi-intensive/wp-content/uploads/2017/02/imam-abdoulahy-ndaw-500x500.jpg">
</a>
<div class="employee-hover-overlay a_m_fly-top-left a_opacity-100 "></div>
</div>
<div class="team-info-wrapper m_7" itemscope="itemscope" itemtype="https://schema.org/Person">
<a class="team-member-name" href="http://developer.designprowebsolutions.com/sufi-intensive/team/imam-abdoulaye-ndaw/">
<span class="team-member-name a_font-16 a_display-block a_font-weight-bold a_text-transform-up a_color-333">Imam Abdoulaye Ndaw</span>
</a>
<span class="team-member-position a_font-12 a_text-transform-up a_display-block a_color-777 a_letter-spacing-1">Imam & Ustadz</span>
<div class="team-member-desc a_margin-top-20 a_margin-bottom-10 a_display-block"></div>
</div>
</div>

How to Print the Particular bootstrap Div

I would like to print a bootstrap div.
It is properly displayed in web browser but when I click on the print button then at print preview, the elements are floating and are not properly displayed.
what should I do to solve this problem ?
Div which I want to print with following this style
What I get the output at printing time which I dont want see on school name at the top
Button which call the print function:
<button class="btn btn-default" onclick="printDiv('printableArea')"><i class="fa fa-print" aria-hidden="true" style=" font-size: 17px;"> Print</i></button>
Print Function:
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
Div which i Want to print
<div class="container right-container col-md-6" id="printableArea" style="display:block;">
<span id="link7">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<h3 id="school_title"><?php echo "$school_name";?> </h3>
<p><p>
<p style="font-size: 1.1em;" id="exam_title">Annual Examination [ 2015-2016 ] <p>
<div class="row">
<div class="col-md-4">
<div class="header-time-date-marks">
<span id="exam_time">Time: 12 AM - 2 PM</span>
<span id="exam_date">Date: 30/12/2016</span>
</div>
</div>
<div class="col-md-8 header-time-date-marks" style="text-align: right;padding-right: 36px;">
<span id="exam_marks">100 Marks</span>
</div>
</div>
</div>
</div>
<hr / id="line" style="margin-top: 13px;">
<div class="row q-question-type-style" id='question_section'>
</div>
</span>
</div>
Check this solution: It is working. The <div> is able to display for print.
Place your <script>-tag above the <html>-tag:
<script>
<html>
https://jsfiddle.net/6cz5br7m/
It's working, just try it on your Editor.
<!-- Your Jquery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<!-- Another Jquery version, which will be compatible with PrintThis.js -->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous">
</script>
<!-- CDN/Reference To the pluggin PrintThis.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/printThis/1.15.0/printThis.js"
integrity="sha512-Fd3EQng6gZYBGzHbKd52pV76dXZZravPY7lxfg01nPx5mdekqS8kX4o1NfTtWiHqQyKhEGaReSf4BrtfKc+D5w=="
crossorigin="anonymous"></script>
<script type="text/javascript">
// important : to avoid conflict between the two version of Jquery
var j = jQuery.noConflict(true);
// define a function that you can call as an EventListener or whatever you want ...
function Print_Specific_Element() {
// the element's id must be unique ..
// you can't print multiple element, but can put them all in one div and give it an id, then you will be able to print them !
// use the 'j' alias to call PrintThis, with its compatible version of jquery
j('#specificElement').printThis({
importCSS: true, // to import the page css
importStyle: true, // to import <style>css here will be imported !</style> the stylesheets (bootstrap included !)
loadCSS: true, // to import style="The css writed Here will be imported !"
canvas: true // only if you Have image/Charts ...
});
}
$("#printBtn").click(Print_Specific_Element);
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- It's very important to include the attribute : media='all'-->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" media='all'
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<style>
#media print {
#page {
/* To give the user the possibility to choise between landscape and portrait printing format */
size: auto;
/* setting custom margin, so the date and the url can be displayed */
margin: 40px 10px 35px;
}
/* Here you can give a custom styling which will be applied only while printing */
a,
button#printBtn {
display: none;
}
}
</style>
</head>
<body>
<div class="container" id="Page">
<div>
this Element will not be printed
</div>
<div id="specificElement" class="bg-primary m-2 p-2 text-center rounded" style="border: 2px solid black;">
<div class="jumbotron">
<h1 class="display-3">
My custom content which I want to print
</h1>
<p class="lead">Another element</p>
<hr class="my-2">
<p>Nothing ... just another element </p>
<button id="printBtn" class="btn btn-success btn-sm shadow">
CLick Me !
<br>
(Dont worry I will not be printed)
</button>
</div>
</div>
</div>
</body>
</html>
Call this function: PrintElem('printableArea')
function PrintElem(elem){
var mywindow = window.open('', 'PRINT', 'height=400,width=600');
var css = "";
var myStylesLocation = "${pageContext.request.contextPath}/ui/css/bootstrap.min.css";
$.ajax({
url: myStylesLocation,
type: "POST",
async: false
}).done(function(data){
css += data;
})
mywindow.document.write('<html><head><title></title>');
mywindow.document.write('<style type="text/css">'+css+' </style>');
// mywindow.document.write('<link rel="stylesheet" href="${pageContext.request.contextPath}/ui/css/bootstrap.min.css" type="text/css" media="print"/>');
mywindow.document.write('</head><body >');
mywindow.document.write('<h1>' + document.title + '</h1>');
mywindow.document.write(document.getElementById(elem).innerHTML);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
mywindow.print();
mywindow.close();
return true;
}
You can try #media print in css.
Like bellow
In css
#media print
{
p.bodyText {font-family:georgia, times, serif;}
.noprint
{
display:none
}
}
In Html
<div class="noprint">
I dont want it on print
</div>
<br><br>
<div>
Prrintable Area
</div>
Fiddle
I was able to look for the section that was undesirably appearing in the print of the modal, and just hiding it, while using your print function:
print() {
let mainLayout = document.querySelector('app-main-layout') as HTMLDivElement;
mainLayout.style.display = 'none';
window.print();
mainLayout.style.display = 'unset';
}
And, make the buttons of my modal go away, by using this css:
#media print {
button.close {display:none !important;}
}
you just need to link your js script properly
<!DOCTYPE html>
<html>
<body>
<div class="container right-container col-md-6" id="printableArea" style="display:block;">
<span id="link7">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<h3 id="school_title"><?php echo "$school_name";?> </h3>
<p><p>
<p style="font-size: 1.1em;" id="exam_title">Annual Examination [ 2015-2016 ] <p>
<div class="row">
<div class="col-md-4">
<div class="header-time-date-marks">
<span id="exam_time">Time: 12 AM - 2 PM</span>
<span id="exam_date">Date: 30/12/2016</span>
</div>
</div>
<div class="col-md-8 header-time-date-marks" style="text-align: right;padding-right: 36px;">
<span id="exam_marks">100 Marks</span>
</div>
</div>
</div>
</div>
<hr / id="line" style="margin-top: 13px;">
<div class="row q-question-type-style" id='question_section'>
</div>
</span>
</div>
<div> <h1>
asdads
</h1>
</div>
<button class="btn btn-default" onclick="printDiv('printableArea')"><i class="fa fa-print" aria-hidden="true" style=" font-size: 17px;"> Print</i></button>
<script>
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>
</body>
</html>

Gallery of floated items. I want to add a class between the lines using jquery

So i will try to explain bit more into detail.
So I've got a gallery with 9 elements floated left creating 3 elements per line like this:
1 2 3 <--line 1
4 5 6 <--line 2
7 8 9 <--line 3
What i am trying to do is when i click on either element i want to add a div bellow the line its part of. For example if i click on element 2 it should add a div after the 3rd element between line 1 and 2.
I tried selecting all the 3rd elements of the line (using :nth-child) but i cant make jquery understand on which line it is.
To be honest i am really confused about how to approach this.
Any ideas would be tremendously helpful.
Thank you.
Constantin Chirila
Later edit:
The code is a mess and its part of a bigger thing so sorry for that.
<a href="#" class="dealer--item" data="hongkong">
<h4 class="dealer--item-title">Hong Kong</h4>
</a>
<a href="#" class="dealer--item" data="australia">
<h4 class="dealer--item-title">Sweden</h4>
</a>
<a href="#" class="dealer--item" data="sweden">
<h4 class="dealer--item-title">Sweden</h4>
</a>
<a href="#" class="dealer--item" data="uk">
<h4 class="dealer--item-title">United kingdom</h4>
</a>
<a href="#" class="dealer--item" data="germany">
<h4 class="dealer--item-title">Germany</h4>
</a>
<a href="#" class="dealer--item" data="netherlands">
<h4 class="dealer--item-title">The Netherlands</h4>
</a>
<a href="#" class="dealer--item" data="canada">
<h4 class="dealer--item-title">Canada</h4>
</a>
<a href="#" class="dealer--item" data="malaysia">
<h4 class="dealer--item-title">Malaysia</h4>
</a>
<a href="#" class="dealer--item" data="thailand">
<h4 class="dealer--item-title">Thailand</h4>
</a>
<a href="#" class="dealer--item" data="japan">
<h4 class="dealer--item-title">Japan</h4>
</a>
<a href="#" class="dealer--item" data="korea">
<h4 class="dealer--item-title">Korea</h4>
</a>
<a href="#" class="dealer--item" data="indonesia">
<h4 class="dealer--item-title">Indonesia</h4>
</a>
<a href="#" class="dealer--item" data="taiwan">
<h4 class="dealer--item-title">Taiwan</h4>
</a>
</div>
Jquery:
$(".dealer--item").click(function (e) {
var idSelector = $(this).attr('data');
e.preventDefault();
$('.dealer--item').not(this).removeClass('is-selected');
$(this).toggleClass("is-selected");
$(".dealer--item:nth-child(3n)").each(function (index) {
$(this).addClass("foo" + index);
});
$('foo0').after($('#' + idSelector)) //this is where i lost it as its not working for other 6 elements
$('#' + idSelector).fadeToggle(300);
});
And content that needs to be added between the lines based on the element clicked.
<div class="dealer--address" id="australia">
Address here
</div>
<div class="dealer--address" id="hongkong">
Address here
</div>
<div class="dealer--address" id="sweden">
Address here
</div>
<div class="dealer--address" id="uk">
Address here
</div>
<div class="dealer--address" id="germany">
Address here
</div>
etc...
Have you considered adding an extra div below the floated left elements and just hiding them initially with display:none; and then using jQuery to show them using the on click function.
$("#clickable element").click(function(){
$("element to show").show();
});
This is the way I do all of my click and display behaviors with jQuery.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<style type="text/css">
.floating {
float: left;
width: 30%;
margin: 1%;
height: 100px;
background: #ffe4c4;
}
.Content {
display:none;
width: 100%;
background: green;
}
#contentOnDisplay {
min-height: 100px;
width: 100%;
float: left;
background: green;
display: block;
}
</style>
</head>
<body>
<div class="Content" id="floating1Content">content for 1</div>
<div class="Content" id="floating2Content">content for 2</div>
<div class="Content" id="floating3Content">content for 3</div>
<div class="Content" id="floating4Content">content for 4</div>
<div class="Content" id="floating5Content">content for 5</div>
<div class="Content" id="floating6Content">content for 6</div>
<div class="Content" id="floating7Content">content for 7</div>
<!-- <div class="Content" id="floating8Content">content for 8</div>
<div class="Content" id="floating9Content">content for 9</div>-->
<div class="floating" id="floating1"></div>
<div class="floating" id="floating2"></div>
<div class="floating" id="floating3"></div>
<div class="floating" id="floating4"></div>
<div class="floating" id="floating5"></div>
<div class="floating" id="floating6"></div>
<div class="floating" id="floating7"></div>
<!-- <div class="floating" id="floating8"></div>
<div class="floating" id="floating9"></div>-->
<script type="text/javascript">
var getLeftMostPositionOfFirstItem = $("#floating1").position().left;
$(document).ready(function() {
$(".floating").click(function() {
var elementID = $(this).attr("id");
$("#contentOnDisplay").remove(); //hides the existing contents
var firstItemOFNextRow = getTheFirstItemOfNextRow(elementID);
getAllTheConstentsOfAdivAndPrepenedIt(firstItemOFNextRow, getTheIdOfFirstItemOfNextRow(elementID));
return false;
});
});
function getTheFirstItemOfNextRow(clickedItemID) {
var getTheIdNumberOfThisItem = parseInt(clickedItemID.replace("floating", ""));
var position = $("#" + clickedItemID).position();
var idOfTheElementToBeInstertedBefore = "";
for (var i = getTheIdNumberOfThisItem + 1; i < $(".floating").length; i++) {
var leftPostitonOfThisItem = $("#floating" + i).position().left;
if (leftPostitonOfThisItem < getLeftMostPositionOfFirstItem*1.5) {
idOfTheElementToBeInstertedBefore = "#floating" + i;
break;
}
}
if (idOfTheElementToBeInstertedBefore.length == "") {
idOfTheElementToBeInstertedBefore = "#floating" + $(".floating").length;
}
return idOfTheElementToBeInstertedBefore;
};
function getTheIdOfFirstItemOfNextRow(elementID) {
return parseInt(elementID.replace("floating", ""));
};
function getAllTheConstentsOfAdivAndPrepenedIt(idToPrepend, IdNumber) {
var htmlOfTheContent = $("#floating" + IdNumber + "Content").html();
htmlOfTheContent = "<div id='contentOnDisplay'>" + htmlOfTheContent + "</div>";
if (IdNumber <= $(".floating").length - getNuumberOfItemsInLastRow()) {
$(idToPrepend).before(htmlOfTheContent);
} else {
$(idToPrepend).after(htmlOfTheContent);
}
return false;
};
function getNuumberOfItemsInLastRow() {
var numberOfColoumns = 0;
for (var i = $(".floating").length; i > 0; i--) {
var leftPostitonOfThisItem = $("#floating" + i).position().left;
numberOfColoumns++;
if (leftPostitonOfThisItem < getLeftMostPositionOfFirstItem * 1.5) {
break;
}
}
return numberOfColoumns;
};
</script>
</body>
</html>

Categories