I'm writing a script that parses an XML file and displays it in html. Here it is:
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
document.write("A: " + date + "<br />B: " + amount + " ISK<br />C: " + balance + " ISK<br /><br /><br /><br />");
});
});
</script>
I want to modify the output of "document.write", so that if the value "amount" is positive, enter the word "green", otherwise, if negative, enter the word "red". I tried to write it as follows:
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
document.write("<script> if (amount >= 0) { document.write("green"); } else{ document.write("red"); } </scri" + "pt>");
});
});
</script>
But in that piece, I get a syntax error in "document.write". What I have written wrong and how could fix it?
I think you can compute the color before writing the output with document.write.
Something like this should work:
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
var color = "green";
if (amount < 0) {
color = "red";
}
document.write("A: " + date + "<br />B: <span style='color:" + color + "'>" + amount + " ISK</span><br />C: " + balance + " ISK<br /><br /><br /><br />");
});
});
</script>
(syntax unchecked)
To get an answer just look, how this code is highlighted. The words 'green' and 'red' are outside the quotes. You should use single quotes (or escape the double quotes).
The other question is why do you use metaprogramming for such a simple task. Just write a condition with two different document.write statements.
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
document.write(amount >= 0 ? "green" : "red");
});
});
</script>
Related
I wanna add an if/else statement that prints "Only Number are accepted", for older browsers, where they allow you to add a string in a input with type=number.
var bttn = document.getElementById("agebttn");
bttn.addEventListener("click", bttnClicked);
function calculate(startingYear) {
var dateObj = new Date()
var currentYear = dateObj.getFullYear()
return currentYear - startingYear;
}
function bttnClicked() {
console.log("bttn clicked");
var age = parseInt(document.getElementById('age').value);
var yearsAlive = calculate(age);
var html = "You entered " + age;
html += "<br />You have been alive for " + yearsAlive + " years";
document.getElementById('answer').innerHTML = html;
}
<body>
<h1>Age Calculator</h1>
<input type="number" id="age" placeholder="Enter your birthyear">
<input type="button" id="agebttn" value="Calc" />
<div id="answer">
</div>
</body>
You can check if you were able to parse int or not using isNaN function here:
function bttnClicked() {
console.log("bttn clicked");
var age = parseInt(document.getElementById('age').value);
if(isNaN(age)){
document.getElementById('answer').innerHTML = "<b>Only Numbers Accepted</b>";
return;
}
var yearsAlive = calculate(age);
var html = "You entered " + age;
html += "<br />You have been alive for " + yearsAlive + " years";
document.getElementById('answer').innerHTML = html;
}
CMIIW
from what i see , you want to print that result from your script logic into your
div tag with ID = answer right? and you want to get only number input?
you would want to use !isNan(age) function to validate your input so when they validate and got not a number input , it will throw you back error message on your else condition
The program breaks if there's a space behind the last number entered. How can I stop the function from breaking if a space is entered? I tried $.trim but couldn't figure out how to get that to work. Also tried an if/else statement
function calculate() {
var numInput = document.getElementById("qty").value;
var numArray = numInput.split(" ").map(function(t) {
return parseInt(t);
});
var minValue = Math.min.apply(null, numArray);
var maxValue = Math.max.apply(null, numArray);
var sumValue = numArray.reduce(function(previous, current) { return previous + current });
var productValue = numArray.reduce(function(previous, current) { return previous * current });
var meanValue = numArray.reduce(function(previous, current) { return previous + current / numArray.length });
document.getElementById("result").innerHTML = 'Min value is: ' + minValue + '<br>' + 'Max value is: '+ maxValue + '<br>' + 'Sum value is: ' + sumValue + '<br>' + 'Product value is: ' + productValue + '<br>' + 'Mean value is: ' + meanValue;
}
function clearAnswer(){
document.getElementById("result").innerHTML = '';
document.getElementById("qty").value = '';
}
<h1> Problem JavaScript</h1> Enter 5 numbers with spaces in between each:
<input type="text" id="qty">
<input type="button" id="go" value="Calculate" onclick="calculate()">
<button type="reset" id="reset" onclick="clearAnswer()">Clear</button>
<div id="result"></div>
I tried $.trim but couldn't figure out how to get that to work.
if you are using jquery trim then ensure that you have included jquery library first.
change
var numArray = numInput.split(" ").map(function(t) {
return parseInt(t);
});
to
var numArray = $.trim( numInput ).split(" ").map(function(t) {
return parseInt(t);
});
or simply
var numInput = $.trim( document.getElementById("qty").value );
use $.trim() to trim the numInput first
Edit:
you don't really need to use jquery only for using trim function here, javascript itself has trim method, which you can use.
$.trim is a jquery function and it works by passing a parameter to trim, which will be trimmed. For instance:
$.trim(" a ")
will result in "a"
Your example would work like this
var numArray = $.trim(numInput).split(" ").map(function(t) {
return parseInt(t);
});
if and only if jquery is defined, that is, you load the library. However, if you want jquery specifically for this purpose, then there is a pure JS function for this purpose as an alternative, called trim. That can be used like this:
var numArray = numInput.trim().split(" ").map(function(t) {
return parseInt(t);
});
My program needs to consist of a for loop, use both input functions already created ( name and number) and totals need to be acquired. I also need to be able to CANCEL and go to my doc.write where i would input name and number. I also need to give the user another chance to type in their name or number if they accidentally typed in number where letters should be and vise-versa. I think i have majority of the structure right, any help would be greatly appreciated!
function inputName() {
var nameIn = prompt("Enter your Name");
while(!isNaN(nameIn)) {
nameIn = prompt("Must contain only letters");
}
return nameIn;
}
/* INPUT NUMBER */
function inputNum(){
var numIn=parseFloat(prompt("Enter the number of hours worked \n 0-60 hours"));
var min=0;
var max=60;
while(numIn>min && numIn>max ){
numIn=prompt("Enter a valid number between 0-60");
return numIn;
}
</script>
<body>
<script type="text/javascript">
//DECLARATIONS
var wage=10.00;
var earned; // hrsWrked*wage
var totHrsWrked=0;
var totEarning=0;
var BR= "
";
var howMany;
var loopControl;
//INPUT & PROCESSING
howMany=parseFloat(prompt("How many employees are you inputing?"));
for(loopControl=1 ; loopControl <= howMany; ++loopControl){
var inpNam=inputName();
var inpNumber=inputNum();
earned= inpNumber*wage;
totEarning+=earned;
totHrsWrked+=inpNumber;
//OUTPUT
document.write("Name: "+ inpNam+ BR);
document.write("Hours Worked: " + inpNumber + BR);
document.write("Money Earned: $ " + earned + BR +BR);
}
document.write("Total Hours Worked: " + totHrsWrked.toFixed(2) + BR);
document.write("Total Earnings: " + "$"+totEarning.toFixed(2)+ BR+BR);
</script>
</body>
</html>
Here's the edited version of your code. :)
<! doctype html>
<html>
<body>
<script>
//DECLARATIONS
var wage=10.00, earned, totHrsWrked=0, totEarning=0, howMany;
//INPUT & PROCESSING
howMany=parseFloat(prompt("No of employees"));
for( var loopControl=1 ; loopControl <= howMany; ++loopControl)
{
var inpNam=inputName();
var inpNumber=inputNum();
earned= inpNumber*wage;
totEarning+= (+earned);
totHrsWrked+= (+inpNumber);
//OUTPUT
document.write("Name: "+ inpNam+ "<br>");
document.write("\n Hours Worked: " + inpNumber + "<br>");
document.write("Money Earned: $ " + earned + "<br><br>");
}
document.write("Total Hours Worked: " + totHrsWrked.toFixed(2)+ "<br>");
document.write("Total Earnings: " + "$"+totEarning.toFixed(2)+ "<br>");
//INPUT NAME
function inputName() {
var nameIn = prompt("Enter your Name");
while(!isNaN(nameIn)) {
nameIn = prompt("Must contain only letters");
}
return nameIn;
}
//INPUT NUMBER
function inputNum(){
var numIn=parseFloat(prompt("Enter the number of hours worked \n 0-60 hours"));
var min=0;
var max=60;
while(numIn<=min || numIn>=max ){
numIn=prompt("Enter a valid number between 0-60");
}
return numIn;
}
</script>
</body>
</html>
This program right now reads in xml code, gets a stock abbreviation, alphabetically sorts them, and then prints them out in an uo list. If you hover over the abbreviations the color will change to red. The goal I'm having is when you hover over an abbreviation, it will show all the data from the xml data just for that company. I tried using the if statement saying if the symbol (abbreviation in xml file) is equivalent to the name (abbreviation in array) then it prints out all the junk for it. The line that prints everything out works correctly in the format I want. I just need to work on the if statement.
What I have figured out is I cannot compare two variables with the ==. Keep in mind symbol is an attribute as well, and name is from an array that stores the symbols. I also tried just saying - if(checkPassword(name, symbol)) - and print it all out as I did in the jQuery code below, but that did not work.
I put a comment next to the if statement I am working on, it's towards the bottom of the jQuery.
HTML:
<body onload="onBodyLoad()">
<div id="stockList"></div>
<br />
<br />
<br />
<div id="stockInfo"></div>
jQuery:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "stocks.xml",
dataType: "xml",
success: function (xml) {
var companyNames = [];
$(xml).find('Stock').each(function () {
var symbol = $(this).attr('symbol');
companyNames.push(symbol);
});
companyNames.sort();
$.each(companyNames, function (index, name) {
$('#stockList').append('<div><li>' + name + '</li></div>');
});
function CheckPassword(val, val2) {
var strInput = val.value;
var strInput2 = val2.value;
if (strInput != strInput2) {
val2.focus();
val2.select();
return false;
} else
return true;
}
$(xml).find('Stock').each(function () {
var company = $(this).find('Company').text();
var symbol = $(this).attr('symbol');
var market = $(this).find('Market').text();
var sector = $(this).find('Sector').text();
var price = $(this).find('Price').text();
var low = $(this).find('Low').text();
var high = $(this).find('High').text();
var amount = $(this).find('Amount').text();
var yieldx = $(this).find('Yield').text();
var frequency = $(this).find('Frequency').text();
$('*').mouseover(function () {
$('#stockList li').text($(this).attr('comparison'));
});
$('#stockList li').hover(
function () {
$(this).css({ color: 'red' }); //mouseover
if (name == symbol) { // THIS IS THE STATEMENT YOU'RE LOOKING FOR PROGRAMMING GODS
$('#stockInfo').append('<div><ol><li>' + "Company = " + company + '</li><br/><li>' + "Market = " + market + '</li><br/><li>' + "Sector = " + sector + '</li><br/><li>' + "Price = " + price + '</li><br/><li>' + "Year Range = " + low + " " + high + '</li></ol><br/>');
}
},
function () {
$(this).css({ color: 'navy' }); // mouseout
$('#stockInfo').empty();
}
);
});
}
});
});
XML sample:
<Products>
<Stock symbol="GOOG">
<Company>Google</Company>
<Market>NASDAQ</Market>
<Sector>Software</Sector>
<Price>$487.80</Price>
<YearRange>
<Low>$331.55</Low>
<High>$488.50</High>
</YearRange>
<Dividend available="false"/>
</Stock>
<Stock symbol="BA">
<Company>Boeing Company</Company>
<Market>NYSE</Market>
<Sector>Aerospace</Sector>
<Price>$79.05</Price>
<YearRange>
<Low>$63.70</Low>
<High>$89.58</High>
</YearRange>
<Dividend available="true">
<Amount>$1.20</Amount>
<Yield>$1.50</Yield>
<Frequency>QTR</Frequency>
</Dividend>
</Stock>
<Stock symbol="MO">
<Company>Altria Group</Company>
<Market>NYSE</Market>
<Sector>Comsumables</Sector>
<Price>$81.70</Price>
<YearRange>
<Low>$68.36</Low>
<High>$85.00</High>
</YearRange>
<Dividend available="true">
<Amount>$3.44</Amount>
<Yield>$4.2</Yield>
<Frequency>ANNUAL</Frequency>
</Dividend>
</Stock>
</Products>
var companyData = [];
$(xml).find('Stock').each(function () {
var symbol = $(this).attr('symbol');
companyNames.push(symbol);
companyData[symbol] = {
company: $(this).find('Company').text(),
symbol: $(this).attr('symbol'),
market: $(this).find('Market').text(),
sector: $(this).find('Sector').text(),
price: $(this).find('Price').text(),
low: $(this).find('Low').text(),
high: $(this).find('High').text(),
amount: $(this).find('Amount').text(),
yieldx: $(this).find('Yield').text(),
frequency: $(this).find('Frequency').text()
};
});
...
$("#stocklist li").hover(function() {
$(this).css({ color: 'red' }); //mouseover
var info = companyData[$(this).text()];
$('#stockInfo').append('<div><ol><li>' + "Company = " + info.company + '</li><br/><li>' + "Market = " + info.market + '</li><br/><li>' + "Sector = " + info.sector + '</li><br/><li>' + "Price = " + info.price + '</li><br/><li>' + "Year Range = " + info.low + " " + info.high + '</li></ol><br/>');
});
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.