use math.max on variables and display corresponding variables - javascript

I have a question with my JavaScript code (I am quite new at this...). I am making a test where I will calculate the score of the participants by using their answers. I have multiple variables where I store these answers. And also the calculation of the score is going ok. Then I have a table with the scores. That is like this:
<script type="text/javascript">
var row1col1var="Fruit";
var rowicol2var="% of how much I love them";
var applep=34; //result from score calcultaion
var row2col1var="Apple";
var bananasp=65; //result from score calcultaion
var row3col1var="Bananas";
document.write('<center><table width="50%" border="0">');
document.write('<tr align="center"><td>' + row1col1var + '<\/td><td>' + rowicol2var + '<\/td><\/tr>');
document.write('<tr align="center"><td>' + row2col1var + '<\/td><td' + applep + "%" + '<\/td><\/tr>');
document.write('<tr align="center"><td>' + row3col1var + '<\/td><td' + bananasp + "%" +'<\/td><\/tr>');
document.write('<\/table><\/center>'); </script>
Here I display the results per "fruit" in a table. What I cannot get to work is this:
I want to pick out the best score (in this case 65, for Bananas) and display: "You love Bananas the most." (ie link 65 to Bananas and display Bananas). I was trying to give the cells an id with the name Apples or Bananas and calling on the id to display it, but this did not work.
My problem breaks down in two pieces:
1. I cannot get math.max to work on variables.
2. I do not know how to link the highest score to its "name" (ie 65 belongs to Bananas).
I hope you can help me!!

You need to use more appropriate way for coding. For storing data, you can use object or array. I am using an array for this example.
Check this :
<html>
<head>
<script type="text/javascript">
function getScore(){
var scoreArr = [];
scoreArr.push(['apple', '35']);
scoreArr.push(['apple', '65']);
var maxPercentage = null;
var lovedFruit = '';
var finalScore = '<center><table width="50%" border="0"><tr align="center"><th>Fruits</th><th>% of how much I love them</th></tr>';
for (var i = 0; i < scoreArr.length; i++) {
finalScore += '<tr align="center"><td>' + scoreArr[i][0] + '</td><td>' + scoreArr[i][1] + "%" + '</td></tr>';
if (maxPercentage === null) {
lovedFruit = scoreArr[i][0];
maxPercentage = parseInt(scoreArr[i][1]);
} else {
if (maxPercentage < parseInt(scoreArr[i][1])) {
lovedFruit = scoreArr[i][0];
maxPercentage = parseInt(scoreArr[i][1]);
}
}
}
finalScore += '</table><br>Result is : ' + maxPercentage + ' belongs to ' + lovedFruit + '</center>';
// WITH JAVASCRIPT
var container = document.createElement('div');
container.innerHTML = finalScore;
document.body.insertBefore(container, null); //append div to end
// WITH JQUERY
// $('body').append(finalScore);
}
</script>
</head>
<body onLoad=getScore()>
</body>
</html>
It will store your data in array and then you can do whatever you want in more sophisticated way.

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));
}

Convert JSON number to stars

Any help would be appreciate. I need to create a slider based on JSON datas from the moviedb API. I created the slider showing the title, the picture and the description within a for loop but the last thing I need to achieve is to get the movie rating but instead of the number I need to show stars (half or full filled according to the datas provided).
I'm stuck and tried different things but it doesn't work. I know it's quite simple but I'm stuck.
Many thanks for any help. Do not hesitate if you need something else because it's my first post on stackoverflow.
Here is the fiddle of my work :
https://jsfiddle.net/y2hbzej8/7/
Here is my JS code to get datas :
JS :
var urlmoviedb = 'https://api.themoviedb.org/3/movie/upcoming?api_key=e082a5c50ed38ae74299db1d0eb822fe';
$(function() {
$.getJSON(urlmoviedb, function (data) {
console.log(data);
for (var x = 0; x < data.results.length; x++) {
var title = data.results[x].original_title;
var descr = data.results[x].overview;
var note = data.results[x].vote_average;
var noteround = Math.round(2 * note) / 2;
var str = "/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg";
var imageurl = str.replace("/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg", "https://image.tmdb.org/t/p/w1280");
var image = imageurl + data.results[x].backdrop_path;
$('#image').append('<li>' + '<h2 class="h2-like mt-4">' + title + '</h2>' + '<p class="note">' + noteround + '</p>' + "<img class='img-fluid mb-4' src='" + image + "'>" + '<p class="descr">' + descr + '</p>' + '</li>');
}
});
Divide the vote_average field of each row by two since values go from 0 to 10. This will give you five stars based values.
I edited your example, I added font-awesome CSS library that will give you lots and lots of icons you can play with. Check them out
Here's the edited example on JSFiddle
var urlmoviedb = 'https://api.themoviedb.org/3/movie/upcoming?api_key=e082a5c50ed38ae74299db1d0eb822fe';
$(function() {
$.getJSON(urlmoviedb, function(data) {
console.log(data);
for (var x = 0; x < data.results.length; x++) {
var title = data.results[x].original_title;
var descr = data.results[x].overview;
var note = data.results[x].vote_average;
var noteround = Math.round(2 * note) / 2;
var str = "/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg";
var imageurl = str.replace("/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg", "https://image.tmdb.org/t/p/w1280");
var image = imageurl + data.results[x].backdrop_path;
//Translate vote average field into number of stars by dividing them by two since vote_average goes from 0 to 10
var numberOfStars = Math.round(note/2);
var stars = '';
for(var index = 0; index < numberOfStars; index++)
stars += '<span class="fa fa-star"/>';
$('#image').append('<li>' + '<h2 class="h2-like mt-4">' + title + '</h2>' + "<img class='img-fluid mb-4' src='" + image + "'>" + '<p class="descr">' + descr + '</p>' + stars + '</li>');
}
});
});

Adding a table from database with javascript

I am seeking help trying to add a new table in my third function called ingredients. I am not very familiar with javascript so I tried to duplicate code from newDosage which is similar to what I need to do. Unfortunately, right now all I see is 0, 1, or 2 and not the actual text from the ingredient table. If anyone can help me correctly call the table, it would be greatly appreciated. Thank you.
Below is my code. The first function pulls the database, the second function uses the results and the third function is where I have tried to add the ingredient table.
function listTreatmentDb(tx) {
var category = getUrlVars().category;
var mainsymptom = getUrlVars().mainsymptom;
var addsymptom = getUrlVars().addsymptom;
tx.executeSql('SELECT * FROM `Main Database` WHERE Category="' + category +
'" AND Main_Symptom="' + mainsymptom + '" AND Add_Symptom="' + addsymptom + '"',[],txSuccessListTreatment);
}
function txSuccessListTreatment(tx,results) {
var tubeDest = "#products";
var len = results.rows.length;
var treat;
for (var i=0; i < len; i = i + 1) {
treat = results.rows.item(i);
$("#warning").append("<li class='treatment'>" + treat.Tips + "</li>");
$("#warning-text").text(treat.Tips);
$('#warning').listview('refresh');
//console.log("Specialty Product #1: " + treat.Specialty1);
if(treat.Specialty1){
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, '1'));
}
if(treat.Specialty2){
$("#products").append(formatProductDisplay('specialty2', treat.Specialty2, treat.PurposeSpecialty2, treat.DosageSpecialty2, '0'));
}
}
}
function formatProductDisplay(type, productName, productPurpose, productDosage, Ingredients, aster){
var newDosage = productDosage.replace(/"\n"/g, "");
if(aster=='1'){ productHTML += "*" }
productHTML+= "</div>" +
"</div>" +
"<div class='productdose'><div class='label'>dosage:</div>" + newDosage + "</div>" +
"<div class='productdose'><div class='label'>ingredients:</div>" + Ingredients +
"</div></li>"
return productHTML;
}
You are missing an argument when you call formatProductDisplay(). You forgot to pass in treat.Ingredient.
Change:
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, '1'));
To:
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, treat.Ingredients, '1'));
Also do the same thing to the similar 'Specialty2' line right below it.

Is there a way to make the subjects in an array clickable?

I'm wanting to make a game using javascript. And part of the game is that there is a 'shop' and the user can click on things in the shop and it effects the score.
var i;
var shop = new Array();
shop[0] = "Bins:" + " " + "5";
shop[1] = "Shops:" + " " + "60";
shop[2] = "Factories: " + " " + "190";
shop[3] = "Warehouses:" + " " + "600";
shop[4] = "Over sies:" + " " + "1,500";
for (i=0; i<shop.length; i++){
document.write(shop[i] + "<br>")
}
That's what the array(s) look like, so would it be possible for a user to click on the object in the 'shop' and for it to effect the overall score of the game?
This seems like a simple js/html thing. To get you rolling, here is what you can try.
// First, define the array in a bit more data-friendly way.
var i, itemEl, valueEl, liEl, qty, totalScore, shop = [];
shop.push({item: 'Bins', quantity: 5});
shop.push({item: 'Shops', quantity: 60});
shop.push({item: 'Factories', quantity: 60190);
shop.push({item: 'Warehouses', quantity: 600});
shop.push({item: 'Over sies', quantity: 1500});
// then, create a javascript handler for clicks. It will increase the total score
totalScore = 0;
function addToScore(val) {
totalScore += val;
alert('New score: ' + totalScore);
}
// finally, output this as HTML. Find an UL element and add each item row.
var itemsContainer = document.getElementById('items');
for (i = 0; i < shop.length; i++) {
// for each shop item, create a text node holding the label
// and a clickable span containing the number. When the user clicks on the number
// the totalScore increasing method will be called.
// you can add other html elements like this, like
// decreasing score, removing the item, whatever
itemEl = document.createTextNode(shop[i].item + ': ');
valueEl = document.createElement('span');
valueEl.setAttribute('onclick', 'addToScore(' + shop[i].quantity + ')');
liEl = document.createElement('li');
liEl.appendChild(itemEl);
liEl.appendChild(valueEl);
itemsContainer.appendChild(liEl);
}
Your HTML should only contain the itemsContainer, like an <ul> element.
<ul id='items'></ul>
This is just an example. There are a few things not done "properly" there, but the code will work. And as you start with this, you'll learn other stuff and then come back and ask how to improve your code.

post data from table row like json format

this is related to my last question(
NOTE: I already got some good answers there). I'm doing a program that will filter. I didn't include this question because i thought that it is easier for me to add text as long as i know how to get the data from the row. But to my dismay, I wasn't able to code a good program til now.
Im currently using this javascript code (thanks to Awea):
$('#out').click(function(){
$('table tr').each(function(){
var td = '';
$(this).find('option:selected').each(function(){
td = td + ' ' + $(this).text();
});
td = td + ' ' + $(this).find('input').val();
alert(td);
});
})
my question is: How to add text before the data from the row? like for example, this code alert
the first row like data1.1 data1.2 data1.3,
then the second row like data2.1 data2.2 data2.3,
I want my output to be displayed like this
[
{"name":"data1.1","comparison":"data1.2", "value":"data1.3"},
{"name":"data2.1","comparison":"data2.2", "value":"data2.3"},
{"name":"data3.1","comparison":"data3.2", "value":"data3.3"}
{.....and so on......}]
but before that happen, i want to check if all the FIRST cell in a row is not empty. if its empty, skip that row then proceed to next row.
is there somebody can help me, please...
Building on my answer to your previous question, see http://jsfiddle.net/evbUa/1/
Once you have your data in a javascript object (dataArray in my example), you can write the JSON yourself, per my example, but you will find it much easier to use a library such as JSON-js (see this also).
// object to hold your data
function dataRow(value1,value2,value3) {
this.name = value1;
this.comparison = value2;
this.value = value3;
}
$('#out').click(function(){
// create array to hold your data
var dataArray = new Array();
// iterate through rows of table
for(var i = 1; i <= $("table tr").length; i++){
// check if first field is used
if($("table tr:nth-child(" + i + ") select[class='field']").val().length > 0) {
// create object and push to array
dataArray.push(
new dataRow(
$("table tr:nth-child(" + i + ") select[class='field']").val(),
$("table tr:nth-child(" + i + ") select[class='comp']").val(),
$("table tr:nth-child(" + i + ") input").val())
);
}
}
// consider using a JSON library to do this for you
for(var i = 0; i < dataArray.length; i++){
var output = "";
output = output + '{"name":"data' + (i + 1) + '.' + dataArray[i].name + '",';
output = output + '"comparison":"data' + (i + 1) + '.' + dataArray[i].comparison + '",';
output = output + '"value":"data' + (i + 1) + '.' + dataArray[i].value + '"}';
alert(output);
}
})
There are two things you need to do here. First get the data into an array of objects, and secondly get the string representation.
I have not tested this, but it should give you a basic idea of what to do.
Edit Please take a look at this JS-Fiddle example I've made. http://jsfiddle.net/4Nr9m/52/
$(document).ready(function() {
var objects = new Array();
$('table tr').each(function(key, value) {
if($(this).find('td:first').not(':empty')) {
//loop over the cells
obj = {};
$(this).find('td').each(function(key, value) {
var label = $(this).parents('table').find('th')[key].innerHTML;
obj[label] = value.innerHTML;
});
objects.push(obj);
}
});
//get JSON.
var json = objects.toSource();
$('#result').append(json);
});
var a = [];
a[0] = "data1.1 data1.2 data1.3"
a[1] = "data1.6 data1.2 data1.3"
var jsonobj = {};
var c = []
for (var i = 0;i
alert(c); //it will give ["{"name":"data1.1","comp...1.2","value":"data1.3"}", "{"name":"data1.6","comp...1.2","value":"data1.3"}"]
u have to include library for function from JSON.stringify from
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
hope this helps

Categories

Resources