For loop not working with innerHTML - javascript

I have a for loop that has innerHTML in it and I cannot figure out why it is not working. The code is as below:
<head>
<script language="javascript">
function afterload()
{
for(var n=1; n<11; n++)
{
document.getElementById("item"+n).innerHTML = window.opener.document.getElementById("item"+n).value;
document.getElementById("prc"+n).innerHTML = window.opener.document.getElementById("prc"+n).value;
document.getElementById("qty"+n).innerHTML = window.opener.document.getElementById("qty"+n).value;
document.getElementById("amt"+n).innerHTML = window.opener.document.getElementById("totl"+n).value;
}
}
</script>
</head>
<body onload="afterload()">
</body>
In the body there are table data with the ids above i.e. item1, prc1, qty1 and amt1 and they run up to 10. the parent window also has input fields with the above ids and they also run to 10. The most confusing thing is that if I remove the for loop and write the actual ids of the fields, it works perfectly.

<head>
<script language="javascript">
function afterload()
{
var item = document.getElementById("item");
var itemvalue = document.getElementById("item").value;
var prc = document.getElementById("prc");
var prcvalue = document.getElementById("prc").value;
var qty = document.getElementById("qty");
var qtyvalue = document.getElementById("qty").value;
var amt = document.getElementById("amt");
var amtvalue = document.getElementById("totl").value;
for(var n=1; n<11; n++)
{
item.innerHTML += (itemvalue + "*" + n + "=" + (itemvalue*n) + "<br />");
prc.innerHTML += (prcvalue + "*" + n + "=" + (prcvalue*n) + "<br />");
qty.innerHTML += (qtyvalue + "*" + n + "=" + (qtyvalue*n) + "<br />");
amt.innerHTML += (amtvalue + "*" + n + "=" + (amtvalue*n) + "<br />");
}
}
</script>
</head>
<body onload="afterload()">
</body>

function innerHtml(n)
{
document.getElementById("item"+n).innerHTML = window.opener.document.getElementById("item"+n).value;
document.getElementById("prc"+n).innerHTML = window.opener.document.getElementById("prc"+n).value;
document.getElementById("qty"+n).innerHTML = window.opener.document.getElementById("qty"+n).value;
document.getElementById("amt"+n).innerHTML = window.opener.document.getElementById("totl"+n).value;
}
function afterload()
{
for(var n=1; n<11; n++)
{
innerHtml(n);
}
}
Hope its help!

Related

Insert "and" before the last element jquery

var swTitle = {};
var favorite = [];
$.each($("input[name='Title']:checked"), function() {
favorite.push($(this).val());
console.log($("input[name='Title']:checked"));
});
swTitle.domain = favorite;
var List = {};
for (var m = 0; m < favorite.length; m++) {
var swTitleObj = [];
$.each($('input[name="' + swTitle.domain[m] + '"]:checked'), function() {
console.log(swTitle.domain[m]);
swTitleObj.push($(this).attr("class"));
console.log(swTitleObj);
});
List[swTitle.domain[m]] = swTitleObj;
}
var swSkillData = " ";
$.each(List, function(key, value) {
console.log(key + ":" + value);
swSkillData += '<li>' + key + '&nbsp' + ':' + '&#160' + value + '</li>';
});
Output will be like:
Fruits:Apple,Banana,Orange,Grapes
I want my output be like:
Fruits:Apple,Banana,Orange & Grapes
I have an array of keys and values separated by commas. I want to insert "and" and remove the comma before the last checked element. Kindly help me out with this issue.
I think you can reduce your code, with an option of adding and before the last element like,
var inputs=$("input[name='Title']:checked"),
len=inputs.length,
swSkillData='',
counter=0;// to get the last one
$.each(inputs, function() {
sep=' , '; // add comma as separator
if(counter++==len-1){ // if last element then add and
sep =' and ';
}
swSkillData += '<li>' + this.value + // get value
'&nbsp' + ':' + '&#160' +
this.className + // get classname
sep + // adding separator here
'</li>';
});
Updated, with and example of changing , to &
$.each(List, function(key, value) {
console.log(key + ":" + value);
var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
swSkillData += '<li>' + key + '&nbsp' + ':' + '&#160' + value + '</li>';
});
Snippet
var value ='Apple,Banana,Orange,Grapes';var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
console.log(value);
Here is an easy and customizable form of doing it.
(SOLUTION IS GENERIC)
$(document).ready(function() {
var ara = ['Apple','Banana','Orange','Grapes'];
displayAra(ara);
function displayAra(x) {
var str = '';
for (var i = 0; i < x.length; i++) {
if (i + 1 == x.length) {
str = str.split('');
str.pop();
str = str.join('');
str += ' and ' + x[i];
console.log(str);
$('.displayAra').text(str);
break;
}
str += x[i] + ',';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Fruits : <span class="displayAra"></span>
str = str.replace(/,(?=[^,]*$)/, 'and')
I solved my own issue. I replaced my last comma with "and" using the above regex. Thanks to Regex!!!

I am trying to modify server side js. which takes an json file as input and render the data to produce html file.

Attached code takes json as input and i am trying to render data using script so that it comes in a proper format.
we need to modify "json to html.txt" server-side js, so that the output in html from the input json .
attached image shows the output at right side.this output must be in format.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var statement, i, j, x = "";
statement = {
"Financial statement:":
["NetIncomeLoss = ","- NetIncomeLossAttributableToNoncontrollingInterest","+ ProfitLoss = "," + IncomeLossFromDiscontinuedOperationsNetO..."," + IncomeLossFromContinuingOperationsInclud... = "," + apd_IncomeLossFromContinuingOperationsBeforeTaxes = "," + OperatingIncomeLoss = "," + SalesRevenueNet"," - CostOfGoodsAndServicesSold"," - SellingGeneralAndAdministrativeExpense"," - ResearchAndDevelopmentExpense"," - RestructuringCharges"," + apd_OtherIncomeExpenseNet"," + IncomeLossFromEquityMethodInvestments"," - InterestExpense"," - IncomeTaxExpenseBenefit","EarningsPerShareBasic = ","+ IncomeLossFromContinuingOperationsPerBasicShare","+ IncomeLossFromDiscontinuedOperationsNetOfTaxPerBasicShare","EarningsPerShareDiluted = ","+ IncomeLossFromContinuingOperationsPerDilutedShare","+ IncomeLossFromDiscontinuedOperationsNetO..."],
"2009-12-31":[251.8,5,256.8,0,256.8,340.3,345,2173.5,1568.6,244.1,27.2,0,11.4,26.9,31.6,83.5,1.19e-06,1.19e-06,0,1.16e-06,1.16e-06,0],"2008-12-31":[68.6,5,73.6,-21.4,95,102.1,114.1,2195.3,1629.7,247,33.2,174.2,2.9,24.5,36.5,7.1,3.3e-07,4.3e-07,-1e-07,3.2e-07,4.2e-07,-1e-07]
}
var spaceCount=[];
var financialStatement=[];
var otherColumns = [];
var output = '<table class="table" style="width:100%;"><tr>';
Object.keys(statement).forEach(function (key, i) {
output += '<th><pre>' + key + '</pre></th>';
if (i > 0){
otherColumns.push(key);
}
});
output += '</tr>';
statement[Object.keys(statement)[0]].forEach(function(val, i){
var total = false;
if (val.indexOf('=') > -1){
total = true;
}
var printValue = '<td><pre>' + val + '</pre></td>';
if (total){
printValue = '<td><pre style="font-weight: bold;text-decoration: underline;">' + val + '</pre></td>';
}
otherColumns.forEach(function(key, j){
if (total){
printValue += '<td><pre style="font-weight: bold;text-decoration: underline;">' + statement[key][i] + '</pre></td>';
}
else
{
printValue += '<td><pre>' + statement[key][i] + '</pre></td>';
}
});
output += printValue + '</tr>';
});
output += '</table>';
document.getElementById("demo").innerHTML = output;
</script>
</body>
</html>

Autocompleting textbox from jquery combobox

I have been following an online tutorial to autocomplete textboxes with database values after the user enters a code greater than 7 characters. I have completed most of what I am trying to achieve however I cannot seem to select a value from the combobox to autocomplete the textbox.
I dont have much javascript experience but I am hoping the problem is something small in what I already have, can someone please recommend the change I need to make to select the value from the combobox.
public ActionResult MultiColumnComboBox(string SearchFor, string ControlId)
{
ViewBag.ProcId = SearchFor.Trim();
ViewBag.ControlBlockId = "block" + ControlId.Trim();
ViewBag.ControlId = ControlId.Trim();
ViewBag.ControlTxtId = "txt" + ControlId.Trim();
return View();
}
public JsonResult LoadComboData(string strSearch, string SearchFor)
{
efacsdbEntities db = new efacsdbEntities();
strSearch = strSearch.Trim();
if (SearchFor.Trim() == "employee" && strSearch.Length>7)
{
var res = (from E in db.allpartmasters
where E.partnum.ToLower().Contains(strSearch.ToLower()) || E.partdesc.ToLower().Contains(strSearch.ToLower())
select new
{
E.partnum,
E.partdesc
}).ToList();
return Json(res, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
<input type="hidden" id="#ViewBag.ProcId" name="#ViewBag.ProcId" value="" />
<input type="hidden" id="#ViewBag.ControlId" name="#ViewBag.ControlId" value="" />
<input type="text" name="#ViewBag.ControlTxtId" id="#ViewBag.ControlTxtId" autocomplete="on" />
<div class="#ViewBag.ControlTxtId renderpart">
<div class="DataBlock">
<div id="#ViewBag.ControlBlockId" style="max-width: 520px;">
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="../../Scripts/json.debug.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".renderpart").hide();
var txtid = "#" + '#ViewBag.ControlTxtId';
var renderpart = "." + '#ViewBag.ControlTxtId';
var selectlinkvalueid = ".Get" + '#ViewBag.ProcId';
$(selectlinkvalueid).on("click", function () {
var value = $(this).attr('id');
var valueText = $(this).attr('title');
$("##ViewBag.ControlId").val(value);
$(txtid).val(valueText);
$(renderpart).slideUp("slow");
});
$(txtid).keyup(function () {
var value = $(txtid).val();
var Procvalue = '#ViewBag.ProcId';
var controlid = "#" + '#ViewBag.ControlBlockId';
value = encodeURI(value);
if (value.length > 2) {
$.ajaxSetup({ cache: false });
$.getJSON("/Test/LoadComboData", { strSearch: " " + value, SearchFor: " " + Procvalue }, function (data) {
$(controlid).html("");
var activecols = $("#hdnActiveColumns").val();
var htmlrow = "";
var tempprocId = '#ViewBag.ProcId';
var jsondata = JSON.stringify(data);
$(controlid).html(CreateDynamicTable(jsondata, tempprocId));
$(renderpart).slideDown("slow");
});
$.ajaxSetup({ cache: true });
}
else {
$(renderpart).slideUp("slow");
}
});
$(txtid).focusin(function () {
var txtid = "#" + '#ViewBag.ControlTxtId';
var value = $(txtid).val();
var Procvalue = '#ViewBag.ProcId';
var controlid = "#" + '#ViewBag.ControlBlockId';
value = encodeURI(value);
if (value.length > 2) {
$.ajaxSetup({ cache: false });
$.getJSON("/Test/LoadComboData", { strSearch: " " + value, SearchFor: " " + Procvalue }, function (data) {
$(controlid).html("");
var htmlrow = "";
var tempprocId = '#ViewBag.ProcId';
var jsondata = JSON.stringify(data);
$(controlid).html(CreateDynamicTable(jsondata, tempprocId));
$(renderpart).slideDown("slow");
});
$.ajaxSetup({ cache: true });
}
else {
$(renderpart).slideUp("slow");
}
});
function CreateDynamicTable(objArray, tempprocId) {
var array = JSON.parse(objArray);
var str = '<table style="width:100%;">';
str += '<tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index + '</th>';
}
str += '</tr>';
str += '<tbody>';
var flag = false;
var ids;
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr>' : '<tr>';
for (var index in array[i]) {
if (flag == false) {
ids = array[i][index];
flag = true;
}
str += '<td><a id="' + ids + '" class="Get' + tempprocId + '" title="' + array[i][index] + '" href="#">' + array[i][index] + '</a></td>';
}
str += '</tr>';
}
str += '</tbody>';
str += '</table>';
return str;
}
});
$(document).click(function (evt) {
var renderpart = "." + '#ViewBag.ControlTxtId';
var theElem = (evt.srcElement) ? evt.srcElement : evt.target;
if (theElem.id == "main" || theElem.id == "sub1") {
$(renderpart).slideUp("fast");
}
});
</script>
Here is the link to the tutorial I was following as well.
Create Multiple column autocomplete combobox

How to embed images from Flickr so image appears on website?

I was wondering how I could embed pictures from FLICKR onto the website, right now, I can only get the URL's of the image, but I wanted to get the whole image with it. Here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
API_KEY = 'YOURAPIKEY'; //INSERT API KEY
USER_ID = '28858578#N06'; //ENTER USER ID
var photolist = [];
$.getJSON('https://www.flickr.com/services/rest/?method=flickr.people.getPhotos&api_key=' + API_KEY + '&user_id=' + USER_ID + '&format=json&jsoncallback=?', function(rest) {
var numPhotos = rest.photos.pages;
for (var u =1; u < numPhotos + 1; u++) {
$.getJSON('https://www.flickr.com/services/rest/?method=flickr.people.getPhotos&api_key=' + API_KEY + '&user_id=' + USER_ID + '&format=json&page=' + u + '&jsoncallback=?', function(results) { var targetDiv = $('#fotolist')
for (var m =0; m < results.photos.total; m++) {
targetDiv.append("https://www.flickr.com/" +
results.photos.photo[m].owner + "/" + results.photos.photo[m].id + "<br />");
photolist.push("https://www.flickr.com/" + results.photos.photo[m].owner + "/" + results.photos.photo[m].id);
}
});
}
});
});
</script>
</head>
<body>
<div id="fotolist">
</div>
</body>
</html>
if photolist contains array of links of images
var fotolist = $('#fotolist');
jQuery.each(photolist , function(index, value){
fotolist.append('<img src="'+value+'">');
});

Storing data in JavaScript array

This is my jsp code where I am trying to push some data in javaScript array.
<%
int proListSize = proList.size();
ProfileDAO proDAO = null;
for(int i = 0, j=1; i < proListSize; i++){
proDAO = (ProfileDAO)proList.get(i);%>
entireArray.push(<%= proDAO.getNetworkmapId()%> + ":"+<%=proDAO.getAssetId()%> + ":" + <%= proDAO.getCode()%>);
<%} %>
And this is the function where I am trying to use it by using pop function.
function GenDemographicTag() {
var ptag = "<!-- Begin "+networkNameToUpperCase+" -->\n" ;
var t = "";
if (WhiteTagLabelDomain) {
ptag += "<iframe src=\"http://"+WhiteTagLabelDomainTrim+"/jsc/"+folderName+"/dm.html?";
} else {
ptag += "<iframe src=\"http://"+cdnName+"/jsc/"+folderName+"/dm.html?";
}
ptag += "n="+networkId+";";
for(var i = 0;i< entireArray.length;i++){
var combinedString = entireArray.splice(1,1);
var rightSide = combinedString.split(':')[0];
var middle = combinedString.split(':')[1];
var leftSide = combinedString.split(':')[2];
t = "";
if ( $("proElementEnable_"+rightSide) && $("proElementEnable_"+leftSide).checked) {
if ( middle == "1") {
if ( $("zip").value.length <= 0) {
t = "0";
} else {
t = $("zip").value;
}
} else if ( $("targetList_"+rightSide) && $("targetList_"+rightSide).length > 0 && $("targetList_"+rightSide).options[0].value != "-1") {
t = makeProelementList($("targetList_"+rightSide));
}
ptag += leftSide+"=" + t+ ";";
}
proDAO = null;
}
ptag += "\" frameborder=0 marginheight=0 marginwidth=0 scrolling=\"no\" allowTransparency=\"true\" width=1 height=1>\n</iframe>\n<!-- end "+networkNameToUpperCase+" -->\n";
document.forms[0].tag.value = ptag;
}
Basically I am trying to get the data from proList and store it in javaScript array(entireArray)...so that I can use in the javascript function..but after doing the above I get a javaScript error as follow:
entireArray.push(3 + ":"+3 + ":" + d3);
entireArray.push(185 + ":"+5 + ":" + d4);
entireArray.push(2 + ":"+2 + ":" + d2);
entireArray.push(186 + ":"+5 + ":" + d9);
entireArray.push(183 + ":"+5 + ":" + d6);
entireArray.push(184 + ":"+5 + ":" + d7);
entireArray.push(187 + ":"+5 + ":" + da);
entireArray.push(445 + ":"+5 + ":" + db);
Reference Error:d3 is not defined.
what is the exact problem..?
The return type of splice is an ARRAY , so you can try following code
var combinedString = entireArray.splice(1,1);
var rightSide = combinedString[0].split(':')[0];
var middle = combinedString[0].split(':')[1];
var leftSide = combinedString[0].split(':')[2];
d3 should be in quotes. "d3"
You need to put the out of JSP in quotes.
entireArray.push(<%= proDAO.getNetworkmapId()%> + ":"+<%=proDAO.getAssetId()%> + ":" + '<%= proDAO.getCode()%>');

Categories

Resources