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";
}
Related
this is my card where i have passed the title and image
<div class="row">
<div class="col-sm-4">
<div class="card" style="width: 200px; background-color: black;" onclick="pass()">
<img class="card-img-top" src="{{ image[0] }}" alt="k" style="width: 180px;">
<div class="card-body">
<a href="{{ url_for('info'}}">
<h5 class="card-title">{{ book[0] }}</h5>
</a>
</div>
</div>
</div>
how to get the value from the a tag and img tag and send it to the particular route ie /info, this is my scripts where i tried to get value
<script>
function pass(){
var a = document.getElementByTagName('a')
var img =document.getElementByTagName('img')
}
</script>
Try this Js code and check your console
<script>
function pass(){
var a = document.getElementsByTagName('a');
var img =document.getElementsByTagName('img');
console.log(a[0].outerHTML);
console.log(img[0].outerHTML);
}
</script>
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>
}
This is the site in question: driglight.com/Learn5.html
The purpose of this site is to click the audio and then choose which image you believe to be the correct representation of the note that was played.
I want to randomize the audio and answers every time the page is refreshed.
When the audio is randomized I need to make sure that the audio that is chosen has it's matching correct answer of an image also chosen and placed randomly among the answers. Also,when any possible answer image is clicked, a div will appear that says 'Good Job!' or 'incorrect'. So when the correct answer is randomized it will need to have the 'Good Job' div to follow it.
Here is the code in html:
<!DOCTYPE html>
<head>
<title>Learn</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-responsive.css">
<link rel="stylesheet" href="css/custom-styles.css">
<link rel="stylesheet" href="css/font-awesome.css">
<link rel="stylesheet" href="css/component.css">
<link rel="stylesheet" href="css/font-awesome-ie7.css">
<script src="js/stuff.js"></script>
<!-- <script src="js/Timhasnoinput.js"></script> -->
</head>
<body>
<!--[if lt IE 7]>
<p class="chromeframe">You are using an <strong>outdated</strong> browser. Please upgrade your browser or activate Google Chrome Frame to improve your experience.</p>
<![endif]-->
<!-- This code is taken from http://twitter.github.com/bootstrap/examples/hero.html -->
<div class="header-wrapper">
<div class="container">
<div class="row-fluid">
<div class="site-name">
<h1>Music Website</h1>
</div>
</div>
</div>
</div>
<div class="container">
<div class="menu">
<div class="navbar">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<i class="fw-icon-th-list"></i>
</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active">Home</li>
<li>Learn</li>
<li>Contact</li>
</ul>
</div><!--/.nav-collapse -->
</div>
<div class="mini-menu">
<label>
<select class="selectnav">
<option value="#" selected="">Home</option>
<option value="#">→ Hello</option>
<option value="#">→ Something else here</option>
<option value="#">→ Another action</option>
<option value="#">→ Something else here</option>
<option value="#">About</option>
<option value="#">Learn</option>
<option value="#">Contact</option>
</select>
</label>
</div>
</div>
</div>
<div class="container bg-white">
<div class="row-fluid">
<div class="span12 ">
<div class="main-caption">
<h1>Music Website</h1>
<h6>Learning Music</h6>
</div>
<div class="Timmy2">
<h4>< Lesson 2</h4>
<h6></h6>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container bg-white">
<div class="row-fluid">
<div class="span12">
<div class="banner">
<div class="audiobuttonholder">
<div class="audioholder" style="padding-bottom:24px;">
<audio controls id="audio1">
hello
</audio>
</div>
<div class="buttonholder"; style="position: absolute; left: 10px; top: 40px;">
</div>
<div class = "numberPage">
Pg. 3 Trebble Cleff
</div>
<div class = "control">
<ul>
<div id="div1" style="display:none; float: right; margin-right: 120px;
margin-top: 40px;" >
<img id=div1image imageC="incorrect.png" src="incorrect.png"></img>
</div>
<input type="image" id="myimage1" style="height:200px;width:200px;
onclick="showDivOne()" />
</ul>
<ul>
<div id="div2" style="display:none; float: right; margin-right: 120px;" >
<img id=div2image imageC="incorrect.png" src="incorrect.png" />
</div>
<input type="image" id="myimage2" style="height:200px;width:200px; padding-
top:24px;" onclick="showDivTwo()"/>
</ul>
<ul>
<div id="div3" style="display:none; float: right; margin-right: 120px;
padding-top: 40px;" >
<img id=div3image imageC="incorrect.png" src="incorrect.png"></img>
</div>
<input type="image" id="myimage3" style="height:200px;width:200px;padding-
top:24px;" onclick="showDivThree()"/>
</ul>
<ul>
<div id="div4" style="display:none; float: right; margin-right: 120px;
margin-top: 40px;" >
<img id=div4image imageC="incorrect.png" src="incorrect.png"></img>
</div>
<input type="image" id="myimage4" style="height:200px;width:200px;"
onclick="showDivFour()" />
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="featured-images">
<ul class="grid effect-8" id="grid">
<li>
<div class="block">
<div class="Timmy2">
<h4>< Lesson 2</h4>
<h6></h6>
</div>
</div>
</li>
</ul>
<div class="block-content">
<div class="user-info">
<h4>Home</h4>
<h6> </h6>
</div>
<div class="user-info">
<h4>Learn</h4>
<h6> </h6>
</div>
<div class="user-info">
<h4>Contact</h4>
<h6> </h6>
</div>
</div>
</div>
</div>
</div>
<script src="js/jquery-1.9.1.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/masonry.pkgd.min.js"></script>
<script src="js/imagesloaded.js"></script>
<script src="js/classie.js"></script>
<script src="js/AnimOnScroll.js"></script>
<script>
new AnimOnScroll( document.getElementById( 'grid' ), {
minDuration : 0.4,
maxDuration : 0.7,
viewportFactor : 0.2
} );
</script>
<script>
$('#myCarousel').carousel({
interval: 1800
});
</script>
</body>
</html>
And here is the code in Javascript:
function showDivFour() {
document.getElementById('div4').style.display = "block";
}
function showDiv() {
document.getElementById('welcomeDiv').style.display = "block";
}
function showDivOne() {
document.getElementById('div1').style.display = "block";
}
function showDivTwo() {
document.getElementById('div2').style.display = "block";
}
function showDivThree() {
document.getElementById('div3').style.display = "block";
}
// THIS SHOULD BE THE BETTER ONE
var correctFileC = $('#div1image').attr("div_answer");
var correctFileC = $('#div2image').attr("div_answer");
var correctFileC = $('#div3image').attr("div_answer");
var correctFileC = $('#div4image').attr("div_answer");
var correctFile1 = $('#myimage1').attr("div_if");
var correctFile2 = $('#myimage2').attr("div_if");
var correctFile3 = $('#myimage3').attr("div_if");
var correctFile4 = $('#myimage4').attr("div_if");
var audio_1 = ["LowATrebbleCleffPianoVC.mp3","LowETrebbleCleffPianoVC.mp3",
"LowGTrebbleCleffPianoVC.mp3","MidBTrebbleCleffPianoVC.mp3",
"MidCTrebbleCleffPianoVC.mp3","MidDTrebbleCleffPianoVC.mp3"];
var rand_audio_1 =
audio_1[Math.floor(Math.random()*audio_1.length)].getElementByName.
(audioholder.innerHTML(rand_audio_1);
function div_if(){
if(audio_1[0]){
var R1 = ["myimage1","TrebbleCleffLowA.gif"],["myimage2","TrebbleCleffLowA.gif"],["myimage3","TrebbleCleffLowA.gif"],["myimage4","TrebbleCleffLowA.gif"];
if[R1(var i=0; i<R1.length;i++).length=4];
} else if(audio_1[1]){
var R2 = ["myimage1","LowE.gif"],["myimage2","LowE.gif"],["myimage3","LowE.gif"],["myimage4","LowE.gif"];
if[R2(var i=0; i<R2.length;i++).length=4];
do nothing
} else if(audio_1[2]){
var R3 = ["myimage1","LowG.gif"],["myimage2","LowG.gif"],["myimage3","LowG.gif"],["myimage4","LowG.gif"];
if[R3(var i=0; i<R3.length;i++).length=4];
do nothing
} else if(audio_1[3]){
var R4 = ["myimage1","MidB.gif"],["myimage2","MidB.gif"],["myimage3","MidB.gif"],["myimage4","MidB.gif"];
if[R4(var i=0; i<R4.length;i++).length=4];
do nothing
} else if(audio_1[4]){
var R5 = ["myimage1","MidC.gif"],["myimage2","MidC.gif"],["myimage3","MidC.gif"],["myimage4","MidC.gif"];
if[R5(var i=0; i<R5.length;i++).length=4];
do nothing
{ else if(audio_1[5]){
var R6 = ["myimage1","MidD.gif"],["myimage2","MidD.gif"],["myimage3","MidD.gif"],["myimage4","MidD.gif"];
if[R6(var i=0; i<R6.length;i++).length=4];
do nothing
} else if{
L1.Push(R);
} else if{
L1.Push(R1)
} else if{
L1.Push(R2)
} else if{
L1.Push(R3)
} else if{
L1.Push(R4)
}
function div_answer(){
if(R[0]){
document.getElementById(div1).innerHTML(divC);
divC.src='GoodJob.png'{
else if(R[1]){
document.getElementById(div2).innerHTML(divC);
divC.src='GoodJob.png'
}
else if(R[2]){
document.getElementById(div3).innerHTML(divC);
divC.src='GoodJob.png'
}
else {
document.getElementById(div4).innerHTML(divC);
divC.src='GoodJob.png'
}
}
}
I assume every audio fragment will have an image? So with that in mind, you create a random index to select an audio fragment (which you already do). Why don't you store that index in a variable and associate the image fragment with it?
Another option would be to create an object. So you make your array with audiofragments and then you initialize a new JS object, and assign the names of the images to 'properties' with your audiofragment as key. Like this:
var images = {};
images[audioname] = image-name;
***Do this for each audiofragment of course***
That way you can just ask the image from your images-object, using the property audioname.
When the page renders, place some value inside the attributes for the images or div:
<img id=myimage data-audio-file="xyz123.mp3" src="...." />
<div data-audio-file="xyz123.mp3" src="...." >My Content</div>
Read the attribute out when it's time to take some action:
var correctFile = $('#myimage').attr("data-audio-file");
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>
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