Variable error in function called in InnerHTML - javascript

I am new to coding, and am facing an issue calling a function from innerhtml. I suspect the issue may be with the innerhtml syntax.
The problematic section is:
document.getElementById('arrowback').innerHTML = "<a href='#' onclick='return imtest(icount,imname);'><img src=/Images/ib/A2.png></a>";
If i change the the syntax to the below then it works for icount, which is a numeric value, not for imname:
document.getElementById('arrowback').innerHTML = "<a href='#' onclick='return imtest("+icount+");'><img src=/Images/ib/A2.png></a>";
I would like to call the imtest function with 2 variables through the innerhtml method. Below is the full code for reference:
<script type="text/javascript">
function clicker(buildname, imname, icount){
var displaybox=document.getElementById('displaybox');
if (displaybox.style.display === "none") {
alert(imname);
document.getElementById('imagebox').innerHTML = "<img src=" + imname + icount+".jpg height='400'>";
document.getElementById('arrowback').innerHTML = "<a href='#' onclick= 'return imtest(icount,imname);'><img src=/Images/ib/A2.png></a>";
document.getElementById('btitle').innerHTML = buildname;
} else {
document.getElementById('displaybox').style.display = "none";
}
return false;
}
function imtest(icount, imname) {
alert(icount);
}
</script>

You just need to add quotes around imname:
document.getElementById('imagebox').innerHTML = '<img src="' + imname + icount + '.jpg" height="400">';
document.getElementById('arrowback').innerHTML = '<img src="/Images/ib/A2.png">';
By the way, you forgot the quotes around both src attribute values, I've added them, and I've took the liberty of changing the quotes you use to have double quotes in your HTML.
See this codepen.

Working code...
Javascript
function imtest(icount, imname){
alert("icount:" + icount + "\n imname: " + imname);
}
function clicker(buildname,imname,icount){
var displaybox=document.getElementById('displaybox');
if(displaybox.style.display == "none"){
displaybox.style.display = "block";
document.getElementById('imagebox').innerHTML = "<img src='" + imname + icount+".jpg' height='400'>";
document.getElementById('arrowback').innerHTML = "<a onclick='return imtest(" + icount + "," + '"' + imname + '"' + ");'><img src='Images/ib/A2.png'></a>";
document.getElementById('btitle').innerHTML = buildname;
}else{
document.getElementById('displaybox').style.display = "none";
}
}
HTML
<div id="displaybox" style="display: none;">
<h1 id="btitle"></h1>
<div id="imagebox"></div>
<div id="arrowback"></div>
</div>
<button onclick="clicker('buildname', 'imname', 'icount');">Clicker</button>

In imtest function you are passing only one parameter and on onclick you are accepting two parameter.Check it
While accepting you shoulde write like this.
document.getElementById('arrowback').innerHTML = '<img src="/Images/ib/A2.png">';

Related

Trying to find input variables created dynamically in HTML page with jQuery [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I am trying to find specific input variables that I do append in my div based on the user requests.
Once the input variables are created I need to validate the content in the input tags before I can proceed. But I am not able to find those variables in jQuery..
Any help is appreciated.
$("#txtNoOfAccounts").on("focusout", function () {
var count = parseInt($("#txtNoOfAccounts").val());
$("#lblSuccess").text(' ');
$("#lblError").text(' ');
if (count.toString() != "NaN") {
$("#accountDiv").empty();
for (var i = 0; i < count; i++) {
$("#accountDiv").append(
"<div class='divTableRow' style='width: 100%'>" +
"<div class='divTableCell' style='width: 40%;padding-left:0;'>" + "<input type='text' name='AccountNo_" + i.toString() + "'" + " class='txtAccountNo' /></div>" +
"<div class='divTableCell' style='width: 40%'>" + "<input type='text' name='Suffix_" + i.toString() + "'" + " class='txtSuffix' /></div>
</div>")
}
}
});
How do I find txtSuffix input variables.
I tried:
$('.txtSuffix').focusout(function (e) {
alert("Control Found");
});
I am not able to find those variables with jQuery.
Any help is appreciated.
Using jQuery, one way to solve this problem is to use the .on() Event Handler Attachment
$("#txtNoOfAccounts").on("focusout", function() {
var count = parseInt($("#txtNoOfAccounts").val());
$("#lblSuccess").text(' ');
$("#lblError").text(' ');
if (count.toString() != "NaN") {
$("#accountDiv").empty();
for (var i = 0; i < count; i++) {
$("#accountDiv").append(
"<div class='divTableRow' style='width: 100%'>" +
"<div class='divTableCell' style='width: 40%;padding-left:0;'>" + "<input type='text' value='no event' name='AccountNo_" + i.toString() + "'" + " class='txtAccountNo' /></div>" +
"<div class='divTableCell' style='width: 40%'>" + "<input type='text' value='with focusout event' name='Suffix_" + i.toString() + "'" + " class='txtSuffix' /></div></div>")
}
}
});
$(document).on('focusout', '.txtSuffix', function() {
alert('Test');
});
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
</head>
<body>
<input type="text" id="txtNoOfAccounts">
<div id="accountDiv">
</div>
</body>
</html>
It is important to make sure that all objects with this class .txtSuffix will follow this behavior.

Increment javascript variable function onclick

This the page I'm working on:
http://gacc.nifc.gov/gbcc/predictive/PSA_ERCmap/Dev/PSAERCmap1.html
When you click on a shaded area the chart associated with the area pops up. What I'm trying to figure out is how to get the "Next PSA" link at the bottom to advance the chart in the popup to the next PSA every time you click it. I've figured out how to get it to advance by one PSA, but can't get it past that one. You'll see if you click on the link.
I have a function (called replace) that replaces the image source for the chart with a link to the next PSA number up. However, I can't figure out how to get it to increment. I tried PSA++ and PSA=PSA1 but neither of them work.
Here's my code:
<title>DEV PSA ERC Map DEV</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function overlay(a) {
PSA = a.id;
var numeric = a.id.replace('GB', '');
PSAnum = Number(numeric)
PSA1 = PSAnum + 1;
nextPSA = ('0' + PSA1).slice(-2);
var overlayContent = '';
overlayContent += '<div id="overlay">';
overlayContent += '<div>';
var imgsrce = '';
imgsrce += 'Charts/WebCharts/GB';
imgsrce += numeric;
imgsrce += '/ERCGraph.PNG';
overlayContent += '<img id="chartimage" src="';
overlayContent += imgsrce;
overlayContent += '" />';
overlayContent += '<br /><b><h1> Close</b></h1>';
overlayContent += '<b><h1> Next PSA</b></h1>';
overlayContent += '</div>';
overlayContent += '</div>';
$("#overlay").replaceWith(overlayContent);
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
if (el.style.visibility == "visible") {
//el.style.visibility="hidden";
}
} //end of overlay function
function replace(a) {
image = document.getElementById('chartimage');
console.log(image.src);
console.log(PSA);
image.src = 'Charts/WebCharts/GB';
image.src += nextPSA;
image.src += '/ERCGraph.PNG';
PSA++;
console.log(PSA);
} //end of replace function
$('.overlay-bg').click(function() {
closePopup();
});
function closePopup() {
el = document.getElementById("overlay");
el.style.visibility = "hidden";
}
$(function() {
$.get("getDate.php", function(data) {
document.getElementById("timestamp").innerHTML = "<b>RAWS observations updated on " + data + "</b>";
});
});
var file;
file = 'GB_PSAdata_Real.js';
$.getJSON(file, function(events) {
var gbname = Object.keys(events);
var divContent = '';
divContent += '<div id="map">';
divContent += '<map name="mapmap">';
for (i = 0; i < gbname.length; i++) {
var PSA = (gbname[i]);
JSONcoords = events[PSA][0].Coords;
JSONcoordString = JSONcoords.toString();
divContent += '<area id="' + PSA + '" href="#" shape="poly" coords="';
divContent += JSONcoordString;
divContent += '" onclick="overlay(this)">';
// console.log(divContent)
}
divContent += '</map>';
divContent += '<img src="GetPSAavg.php" width="826" height="1005" usemap="#mapmap" />';
divContent += '</div>';
$("#map").replaceWith(divContent);
//$("#overlay").replaceWith(overlayContent);
;
})
</script>
</head>
<div id="overlay">
</div>
<body>
<div id="header">
<img src="PSlogo.png" style="height:75px">
<img src="GBlogo.png" style="height:75px">
<span><b>Great Basin ERC Percentiles</b> *Experimental*</span>
</div>
<div id="main">
<div id="map"></div>
<div id="timestamp">RAWS Observations Updated</div>
<div id="legend">
<img src="LegendFull2.png" id="legendIMG">
</div>
</div>
</body>
</html>
You need to move the code that increments the number into the replace() function, so it gets executed each time replace() is called. Currently it is executed only once when the overlay() function is called.
First, explicitly declare a global variable (outside of any function):
var currentPSANum = null;
Place this line inside the overlay() function:
currentPSANum = Number(a.id.replace('GB',''));
Then use the following for the replace() function:
function replace(a) {
currentPSANum++;
var image = document.getElementById('chartimage');
image.src = 'Charts/WebCharts/GB' + ('0' + currentPSANum).slice(-2) + '/ERCGraph.PNG';
}

To identify second mouse click on the same cell within the grid

i want to place an image inside the cell on the first click and another image on the second click at the same position. In order to do that i tried writing onclick function in the tag..but as its written within functions it wont work..is there any other way to achieve the need ? plz help?
JS for placing the images on click:-
function changeColor1(elem)
{
elem.innerHTML = '<img src="images/atom1.png" width="20px" height="20px" onclick=changecolor2(this) />';
//alert("Row Index is:"+elem.parentNode.rowIndex+elem.cellIndex);
var x= elem.cellIndex;
var y= elem.parentNode.rowIndex;
click_count(x,y);
}
function changeColor2(elem)
{
elem.innerHTML = '<img src="images/2circles.png" width="20px" height="20px" onclick=changecolor3(this) />';
//alert("Row Index is:"+elem.parentNode.rowIndex+elem.cellIndex);
var x= elem.cellIndex;
var y= elem.parentNode.rowIndex;
click_count(x,y);
}
code for making the grid:
$rows = 7; // define number of rows
$cols = 6;// define number of columns
echo "<center>";
echo "<table border='1' cellspacing=0 cellpadding='35' pixels'>";
for($tr=0;$tr<$rows;$tr++){
echo "<tr>";
for($td=0;$td<$cols;$td++){
echo "<td onclick=\"changeColor1(this)\" >&nbsp &nbsp</td>";
}
echo "</tr>";
Try this:
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
function changeColor2(elem)
{
if(!hasClass(elem, 'clicked')){
//clicked first time
elem.className = elem.className + " clicked";//add clicked class to element on first click
elem.innerHTML = '<img src="images/2circles.png" width="20px" height="20px" onclick=changecolor3(this) />';
//alert("Row Index is:"+elem.parentNode.rowIndex+elem.cellIndex);
var x= elem.cellIndex;
var y= elem.parentNode.rowIndex;
click_count(x,y);}
else{
//clicked second time and onward
}
}

How do I put values from a loop in their own DIV tag?

I need help for returning the value from the loop. Here is my javascript code :
get_images = ["01","02","03"];
for(var i=0; i < get_images.length; i++){
images = '<img src="images/' + page_id + '/gallery/01/' + get_images[i] +'.jpg" >';
}
$("#imgs").html(images);
What I want is, I want get all the value " images " from inside the loop and put it into inside the
<div id="imgs"></div>
How do I put the images found in the loop into their own div tag?
Try this..
get_images = ["01","02","03"];
var images ='',
arrLength = get_images.length;
for(var i=0; i < arrLength; i++){
// Here concatenate your values.
images += '<img src="images/' + page_id + '/gallery/01/' + get_images[i] +'.jpg" >';
}
$("#imgs").html(images);
Do you mean to do string append? Right now you're overwriting the images variable in every iteration:
images = images + '<img src="images/' + page_id + '/gallery/01/' + get_images[i] +'.jpg" >';

.html() help dont know how to handle it

...
success: function (reqCode) {
if (reqCode['error_code'] == 1) {
//Generiere Tabelle
$(".done").html(
'<p class="bold center"><?php echo "Besucher ".$month_name[' + reqCode['month'] + ']." ".' + reqCode['year'] + '; ?></p>'
'<canvas id="cvs" width="680" height="250">[No canvas support]</canvas>'
'<script>'
'chart = new RGraph.Line("cvs", ' + reqCode['data_string'] + ');'
'chart.Set("chart.tooltips", ' + reqCode['labels_string'] + ');'
'chart.Set("chart.tooltips.effect", "expand");'
'chart.Set("chart.background.grid.autofit", true);'
'chart.Set("chart.gutter.left", 35);'
'chart.Set("chart.gutter.right", 5);'
'chart.Set("chart.hmargin", 10);' +
'chart.Set("chart.tickmarks", "circle");'
'chart.Set("chart.labels", ' + $reqCode['labels_tooltip'] + ');'
'chart.Draw();'
'</script>'
);
$('.done').fadeOut('slow');
$('.done').fadeIn('slow');
}
}
I don't know why every new line needs its own '..'. Anyway it's not working. Looked into the API reference but found nothing useful :(
Edit: For my second question:
This is what JSON response:
$response['error_code'] = '1';
$response['data_string'] = "[" . join(", ", $data) . "]";
$response['labels_string'] = "['" . join("', '", $labels) . "']";
$response['labels_tooltip'] = "['" . join("', '", $data) . "']";
$response['month'] = $month_name[$month];
$response['year'] = $year;
echo json_encode($response);
There does seem to be something wrong with that <script> tag, but really? You don't need to insert that <script> tag. You're already running JavaScript; just do this:
success: function (reqCode) {
if (reqCode['error_code'] == 1) {
var month_name = <?php echo json_encode($month_name); ?>;
//Generiere Tabelle
$(".done").html(
'<p class="bold center">Besucher ' + month_name[reqCode['month']] + ' ' + reqCode['year'] + '</p>'+
'<canvas id="cvs" width="680" height="250">[No canvas support]</canvas>'
);
var chart = new RGraph.Line("cvs", reqCode['data_string']);
chart.Set("chart.tooltips", reqCode['labels_string']);
chart.Set("chart.tooltips.effect", "expand");
chart.Set("chart.background.grid.autofit", true);
chart.Set("chart.gutter.left", 35);
chart.Set("chart.gutter.right", 5);
chart.Set("chart.hmargin", 10);
chart.Set("chart.tickmarks", "circle");
chart.Set("chart.labels", reqCode['labels_tooltip']);
chart.Draw();
$('.done').fadeOut('slow');
$('.done').fadeIn('slow');
}
}
I've fixed some syntax errors in there, though I can't guarantee that there are none left. Just watch the JavaScript console for errors.
You should have a container element with class done on it, like:
<div class="done" />
In addition, you can short:
$('.done').html('..all the html..').fadeOut('slow').fadeIn('slow');
Moreover, as Vivin Paliath said, you should concat all the strings in the html using +
'<a>'+
'asdsad'+
'</a>'
Good Luck!
You need + signs
success: function (reqCode) {
if (reqCode['error_code'] == 1) {
//Generiere Tabelle
$(".done").html('<p class="bold center"></p>'+
'<canvas id="cvs" width="680" height="250">[No canvas support]'+
'<script>'+
'chart = new RGraph.Line("cvs", ' + reqCode['data_string'] + ');'+
'chart.Set("chart.tooltips", ' + reqCode['labels_string'] + ');'+
'chart.Set("chart.tooltips.effect", "expand");'+
'chart.Set("chart.background.grid.autofit", true);'+
'chart.Set("chart.gutter.left", 35);'+
'chart.Set("chart.gutter.right", 5);' +
'chart.Set("chart.hmargin", 10);' +
'chart.Set("chart.tickmarks", "circle");'+
'chart.Set("chart.labels", ' + $reqCode['labels_tooltip'] + ');'+
'chart.Draw();'+
''
);
$('.done').fadeOut('slow');
$('.done').fadeIn('slow');
}
}
You need to pass a single string to the html() function. Something like:
$(".done").html("<p>hello</p><p>goodbye</p>").
If you need to combine multiple strings you will need to use string concatenation, like:
var combinedString = '<p>hello</p>' + '<p>goodbye</p>'

Categories

Resources