Trying to get this string to appear in a paragraph - javascript

Trying to get this string I have in JavaScript to appear in a paragraph in my HTML page by mousing over another paragraph.
function showInfo()
{
for (i = 0; i < object2; i = i + 1)
{
var myParagraph = "Name of Business: " + info.insurance[i].name + "\nState: " + info.insurance[i].state + "\nDiscount: " + info.insurance[i].discount + "\n" + "(" + i + 1 + "of" + object2 + ")"
}
}
myDiscount.addEventListener("mouseover", showInfo, false);
myDiscount.addEventListener("mouseout", showInfo, false);
<p id="discount">Show me the discounts!</p>
<p id="myP"></p>

If you want to show the next element of the info.insurance array each time you mouse over the paragraph, you shouldn't be using a for loop. That will do it all at once, not once for each mouseover. You need to put the counter in a global variable, and just increment it each time you call the function.
Yuo show it by assigning it to the innerHTML of the paragraph. You also need to use <br> rather than \n to make newlines (unless the style of the paragraph is pre).
var insurance_counter = 0;
function showInfo() {
var myParagraph = "Name of Business: " + info.insurance[insurance_counter].name + "<br>State: " + info.insurance[insurance_counter].state + "<br>Discount: " + info.insurance[insurance_counter].discount + "<br>(" + (insurance_counter + 1) + "of" + object2 + ")";
document.getElementById("myP").innerHTML = myParagraph;
insurance_counter++;
if (insurance_counter >= object2) { // wrap around when limit reached
insurance_counter = 0;
}
}

Related

How to get rid of many IFs and make a system to differ elements?

In this piece of code you can see a JSON request that fetches some data. I need some help to check certain opportunities of minimizing the code and getting iterations with FOR instead of many IFs. Also, it would be nice if you advise anything on the differentiation system (how to make elements differ from each other)
<script type="text/javascript">
function deleteRow0() {
$('p.row0').remove();
};
function deleteRow1() {
$('p.row1').remove();
};
function deleteRow2() {
$('p.row2').remove();
};
function deleteRow3() {
$('p.row3').remove();
};
function deleteRow4() {
$('p.row4').remove();
};
</script>
<script type="text/javascript">
function hello2() {
//GETTING JSON INFO
$.getJSON("https://rawgit.com/Varinetz/e6cbadec972e76a340c41a65fcc2a6b3/raw/90191826a3bac2ff0761040ed1d95c59f14eaf26/frontend_test_table.json", function(json) {
$('#table-cars').css("display", "grid");
for (let counter = 0; counter < json.length; counter++) {
$('#table-cars').append("<p class='row" + counter +" main-text'>" + json[counter].title + "<br/>" + "<span class='sub-text'>" + json[counter].description + "</span>" + "</p>"
+ "<p class='row" + counter +" main-text'>" + json[counter].year + "</p>"
+ "<p id='color" + [counter] + "' class='row" + counter +" main-text'>" + json[counter].color + "</p>"
+ "<p id='status" + [counter] + "' class='row" + counter +" main-text'>" + json[counter].status + "</p>"
+ "<p class='row" + counter +" main-text'>" + json[counter].price + " руб." + "</p>"
+ "<p class='row" + counter +" main-text'>" + "<button class='delete' onclick='deleteRow" + [counter] + "()'>Удалить</button>" + "</p>");
// COLOR TEXT REPLACEMENT
if ($('p#color0').text("red")){
$('p#color0').text("").append("<img src='red.png'>");
}
if ($('p#color1').text("white")) {
$('p#color1').text("").append("<img src='white.png'>");
}
if ($('p#color2').text("black")) {
$('p#color2').text("").append("<img src='black.png'>");
}
if ($('p#color3').text("green")) {
$('p#color3').text("").append("<img src='green.png'>");
}
if ($('p#color4').text("grey")) {
$('p#color4').text("").append("<img src='grey.png'>");
}
// STATUS TEXT REPLACEMENT
if ($('p#status0').text("pednding")) {
$('p#status0').text("").append("Ожидается");
}
if ($('p#status1').text("out_of_stock")) {
$('p#status1').text("").append("Нет в наличии");
}
if ($('p#status2').text("in_stock")) {
$('p#status2').text("").append("В наличии");
}
if ($('p#status3').text("out_of_stock")) {
$('p#status3').text("").append("Нет в наличии");
}
if ($('p#status4').text("in_stock")) {
$('p#status4').text("").append("В наличии");
}
}
});
}
</script>
I expect this to be something like:
1) Iteration: For each p.row(i) {
compare it to many color (json.color)};
2) Any suggestion on differentiation system (i.e. changes in the FOR section, so it gives something easier to work with, not just simple p.row(n)). Of course, if it is possible.
I'm not going to rewrite the entire script, but in principle it would be something like this:
for (i = 0; i < 5; i++) {
var colors = ["red", "white", "black", "green", "grey"];
if ($('p#color' + i).text() == colors[i]){
$('p#color' + i).text("").append("<img src='" + colors[i] + ".png'>");
}
}
#Evik Ghazarian has a quality solution for the Text Translation portion of your script. Since this is the accepted answer, he allowed me to copy his solution so that the answers would be together:
function getTranslate(input) {
var inputMap = {
"pednding": "Ожидается",
"out_of_stock": "Нет в наличии",
"in_stock": "В наличии"
}
var defaultCode = input;
return inputMap[input] || defaultCode;
}
for (let i = 0; i < 5 , i ++){
var text = $("p#status"+i).text();
$("p#status"+i).text("").append(getTranslate(text));
}
Dynamic Iteration Counters
#Barmar mentioned in the comments below that the for loops that set a max iteration via i < 5 should actually be rewritten dynamically. I'll leave it to the OP to decide the best way to do this, but a good example might be something like i < json.length as used in the OP's original for loop.
First of all your code won't work because you are setting the text rather than comparing it. Second, you don't need to compare: just set the img src to text. Like below:
REMEMBER THIS IS FOR COLOR TEXT REPLACEMENT PART OF YOUR QUESTION
for (let i = 0; i < 5 , i ++){
let color = $("p#color"+i).text() + ".png";
$("p#color"+i).text("").append("<img src=" + color + ">");
}
FOR TEXT TRANSLATION YOU CAN USE:
function getTranslate(input) {
var inputMap = {
"pednding": "Ожидается",
"out_of_stock": "Нет в наличии",
"in_stock": "В наличии"
}
var defaultCode = input;
return inputMap[input] || defaultCode;
}
for (let i = 0; i < 5 , i ++){
var text = $("p#status"+i).text();
$("p#status"+i).text("").append(getTranslate(text));
}

Add new line using jQuery concat

Through ajax response I'm passing array data from controller to blade.
On Ajax success I'm looping through array with 2 elements and concatenating string to display later on in my bootstrap popover.
success: function (data) {
var content = "";
var num = 1;
for (var i = 0; i < data.length; i++) {
content = content.concat(num + "." + " " + data[i]);
num++;
}
$("#content").popover({content: content});
}
Result:
I would like to add new line, so that each item or "artikel" would be displayed in new line e.g. :
1.Artikel...
2.Artikel...
I tried to add "\n" (as below) or html break but nothing works, it only appends as string.
content = content.concat(num + "." + " " + data[i] + "\n");
Use this:
content.concat(num + "." + " " + data[i] + "<br/>");
And this:
$("#content").popover({ html:true, content: content });

Is it not possible to use HTML entities in a title attribute?

The above screengrab is from Firefox. The cursor is hovering over the yellow spot at the left hand side of the image. It is an <img> element (well actually it's an image together with an image map containing a single circular <area> element, but I assume this distinction is unimportant) that has been created and styled in JavaScript, including the application of a title attribute (constructed by cutting and gluing strings). How can I get this to behave and show the intended character, an en dash, instead of –? It works for innerHTML (the text "Barrow-In-Furness" in the top middle-left is a div that was also created using JavaScript, and its innerHTML set.)
Edit: In response to question of Domenic: Here is the JavaScript function that builds and applies the title attribute (in addition to performing other jobs):
var StyleLinkMarker = function (LinkNumber, EltA, EltI) {
var AltText = LocationName[LinkStart[LinkNumber]] +
" to " +
LocationName[LinkEnd[LinkNumber]];
if (!EltA) {
EltA = document.getElementById("link_marker_area" + LinkNumber);
EltI = document.getElementById("link_marker_img" + LinkNumber);
}
if (LinkStatus[LinkNumber] === 9) {
var CanBuyLinkCode = BoardPreviewMode ? 0 : CanBuyLink(LinkNumber);
if (CanBuyLinkCode === 0) {
EltI.src = ImagePath + "icon-buylink-yes.png";
AltText += " (you can buy this " + LinkAltTextDescription + ")";
} else {
EltI.src = ImagePath + "icon-buylink-no.png";
AltText += " (you cannot buy this " + LinkAltTextDescription;
AltText += CanBuyLinkCode === 1 ?
", because you aren't connected to it)" :
", because you would have to buy coal from the Demand Track, and you can't afford to do that)";
}
} else if ( LinkStatus[LinkNumber] === 8 ||
(LinkStatus[LinkNumber] >= 0 && LinkStatus[LinkNumber] <= 4)
) {
EltI.src = ImagePath + "i" + LinkStatus[LinkNumber] + ".png";
if (LinkStatus[LinkNumber] === 8) {
AltText += " (orphan " + LinkAltTextDescription + ")";
} else {
AltText += " (" +
LinkAltTextDescription +
" owned by " +
PersonReference(LinkStatus[LinkNumber]) +
")";
}
} else {
throw "Unexpected Link Status";
}
EltA.alt = AltText;
EltA.title = AltText;
};
LocationName is as follows:
var LocationName = [
"Barrow–In–Furness", "Birkenhead", "Blackburn", "Blackpool",
"Bolton", "Burnley", "Bury", "Colne",
"Ellesmere Port", "Fleetwood", "Lancaster", "Liverpool",
"Macclesfield", "Manchester", "The Midlands", "Northwich",
"Oldham", "Preston", "Rochdale", "Scotland",
"Southport", "Stockport", "Warrington & Runcorn", "Wigan",
"Yorkshire"
];
You aren't setting the title attribute, you are setting the title property, which expects text and not HTML (although the setAttribute method also expects a text string).
Generally speaking, when dealing with DOM manipulation, you provide text and not HTML. .innerHTML is the notable exception to this rule.
Here's an easy way to convert from HTML to text:
function convertHtmlToText(value) {
var d = document.createElement('div');
d.innerHTML = value;
return d.innerText;
}
Your code could then be updated to this:
EltA.title = convertHtmlToText(AltText);

Using a list position as a param to a function to pull certain data

function getList()
{
var string2 = "<img src='close.png' onclick='removeContent(3)'></img>" + "<h4>Survey Findings</h4>";
string2 = string2 + "<p>The 15 Largest lochs in Scotland by area area...</p>";
document.getElementById("box3text").innerHTML = string2;
var myList = document.getElementById("testList");
for(i=0;i<lochName.length;i++)
{
if(i<3)
{
var listElement = "<a href='javascript:getLoch(i)'>" + "Loch "+ lochName[i] + "</a>";
var container = document.getElementById("testList");
var newListItem = document.createElement('li');
newListItem.innerHTML = listElement;
container.insertBefore(newListItem, container.lastChild);
}
else
{
var listElement = "Loch "+lochName[i];
var container = document.getElementById("testList");
var newListItem = document.createElement('li');
newListItem.innerHTML = listElement;
container.insertBefore(newListItem, container.lastChild);
}
}
}
This function generates a list with the 1st 3 elements being hyperlinks. When clicked they should call a function call getLoch(i) with i being the position of the item in the list. However when i pass it the value it just give it a value of 15, the full size of the array and not the position.
function getLoch(Val)
{
var str = "<img src='close.png' onclick='removeContent(4)'></img>" + "<h4>Loch " + lochName[Val] +"</h4>";
str = str + "<ul><li>Area:" + " " + area[Val] + " square miles</li>";
str = str + "<li>Max Depth:" + " " + maxDepth[Val] + " metres deep</li>";
str = str + "<li>County:" + " " + county[Val] + "</li></ul>";
document.getElementById("box4").innerHTML = str;
}
There are 2 errors in your code as far as I can see. The first is the way you create your link.
var listElement = "<a href='javascript:getLoch(i)'>" + "Loch "+ lochName[i] + "</a>";
This will actually result in code like this:
<a href='javascript:getLoch(i)'>Loch name</a>
Passing a variable i is probably not what you intended, you want it to pass the value of i at the time your creating this link. This will do so:
var listElement = "<a href='javascript:getLoch(" + i + ")'>" + "Loch "+ lochName[i] + "</a>";
So why does your function get called with a value of 15, the length of your list? In your getList function, you accidently made the loop variable i a global. It's just missing a var in your loop head.
for(var i=0;i<lochName.length;i++)
After the loop finished, i has the value of the last iteration, which is your array's length minus 1. By making i a global, and having your javascript code in the links use i as parameter, getLoch got called with your array length all the time.

JQuery: get a child as you append it

I am appending p tags to a div as I process a json request and would liek to style it according to what is in the request.
$(document).ready(function() {
function populatePage() {
var numberOfEntries = 0;
var total = 0;
var retrieveVal = "http://www.reddit.com/" + $("#addressBox").val() + ".json";
$("#redditbox").children().remove();
$.getJSON(retrieveVal, function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
ups = this.data.ups;
downs = this.data.downs;
total += (ups - downs);
numberOfEntries += 1;
$("#redditbox").append("<p>" + ups + ":" + downs + " " + title + "<p>");
$("#redditbox :last-child").css('font-size', ups%20); //This is the line in question
});
$("#titlebox h1").append(total/numberOfEntries);
});
}
populatePage()
$(".button").click(function() {
populatePage();
});
});
Unfortunately things are not quite working out as planned. The styling at the line in question is applying to every child of the div, not just the one that happens to be appended at the time, so they all end up the same size, not sized dependent on their numbers.
how can I apply a style to the p tags as they are appended ot the div?
Edit: Thanks Fortes and Veggerby both worked, but i went with Fortes in the end because I did.
You can use JQuery's appendTo instead of append. For your example:
$("<p>" + ups + ":" + downs + " " + title + "<p>")
.css('font-size', ups%20)
.appendTo('#redditbox');
Here are the docs for appendTo: http://docs.jquery.com/Manipulation/appendTo
Replace:
$("#redditbox").append("<p>" + ups + ":" + downs + " " + title + "<p>");
with
var p = $("<p>" + ups + ":" + downs + " " + title + "<p>");
$("p", p).css('font-size', ups%20)
$("#redditbox").append(p);
Can probably be condensed even further.
Edit:
Condensed like:
$("#redditbox").append(
$("<p></p>").css('font-size', ups%20).append(ups + ":" + downs + " " + title + "")
);
Certain browsers/versions do not support the :last-child CSS selector. In that case they often ignore it and return all elements matching the remainder of the selector. This is possibly what you are seeing.
As usual IE is one such browser.
veggerby's approach should help you get around the need to use :last-child.

Categories

Resources