How can I assign a javascript variable in html format? - javascript

For example, there is a page like below.
<html>
<head>
<title>Variables!!!</title>
<script type="text/javascript">
var lookatthis = 11;
var one = 22;
var two = 3;
var add = one + two;
var minus = one - two;
var multiply = one * two;
var divide = one/two;
document.write("First No: = " + one + "<br />Second No: = " + two + " <br />");
document.write(one + " + " + two + " = " + add + "<br/>");
document.write(one + " - " + two + " = " + minus + "<br/>");
document.write(one + " * " + two + " = " + multiply + "<br/>");
document.write(one + " / " + two + " = " + divide + "<br/>");
</script>
</head>
<body>
</body>
</html>
I want to assign the javascript variable "lookatthis" on debug console.
//apologise for my ambiguous question. I would rather say,
"I want to assign new value to variable "lookatthis" on this web-page using console on explorer."
Thank you for your kind teaching.)

Open debug console and write there:
lookatthis = 20
But this get you nothing

You can use the log method:
console.log(lookatthis);

Anywhere in your script block after your initial assignment of lookatthis, you can write the value to the console with the command:
console.log(lookatthis);

You achieve it by using prompt function
var lookatthis = prompt('Type the lokaltthis value');

If what you want is to be able to 'set' the value of lookatthis, you can use an input and using jquery or pure js get the value of the input and assign it to 'lookatthis'.
Edit: You can also use in the chrome console: lookatthis=25
but as your script loads when page loads, changes will not be shown but the value will be changed

Related

Unable to display total using append

I am making a food delivery app. I would like that there would be a place whereby it would display the total. Right now, I am unable to display the total amount from multiplying quantity and price. It does not show up on the app.
And, there are no errors on the console too.
Javascript Code:
function _showorderResult(arr) {
var value1 = arr[0].price;
var value2 = arr[0].quantity;
for (var i = 0; i < arr.length; i++) {
result = value1 * value2;
htmlstring = "";
$("#itemimage").html("<img src='" + serverURL() + "/images/" +
arr[i].imagefile + "' width='200'>");
$("#price").html("Price" + ": " + " $" + arr[i].price);
$("#itemname").html("Item" + ":" + arr[i].itemName);
$("#quantity").html("Quanitiy" + ":" + arr[i].quantity);
$("result").append(htmlstring);
$("#requestedDateTime").html("To delivery by" + ":" + arr[i].requestedDateTime);
$("#deliveredDateTime").html("Delivered on" + ":" + arr[i].deliveredDateTime)
}
}
And, there are no errors on the console too.
There were plenty of errors in my console, but there are several mistakes here. The first is that your code is not runnable. Please consider making a minimal, verifiable example.
Next, you are misusing or not properly formatting the append(...) function. That's intended to append HTML elements, not string values.
As the comments suggest, you seem to have confused var result and $("result"). If you're not using the DOM selector, you probably don't want to jQuery-wrap your variables. The proper jQuery-wrap syntax would have been $(result) without the double quotes, but please don't do that either, it doesn't offer any benefit over just var result. htmlstring doesn't contain any actual HTML, so I've renamed it runningTotal instead and add it to the price * quantity. This must be initialized first or you'll get NaN.
Make sure to initialize your variables. To this point, there's some hard-coded indexes such as value1 = arr[0].price which make no sense in this pasted code. We can assume you left these here after troubleshooting. Please clean them up next time.
Finally, this is minor, but be consistent with your object names... e.g. imagefile versus imageFile. It doesn't matter which you choose so as long as you're consistent. This will help find typos down the road.
Here's a working example:
<html>
<img src="" id="itemimage">
<p id="price">Price: $0.00</p>
<p id="itemname">Item: None</p>
<p id="quantity">Quantity: None</p>
<p id="result">Running: None</p>
<p id="requestedDateTime">To delivery by: None</p>
<p id="deliveredDateTime">Delivered on: None</p>
<script>
var order = [{
price: 5,
quantity: 3,
itemName: 'Pizza',
imagefile: 'pizza.png',
requestedDateTime: '12:00',
deliveredDateTime: '12:30'
}];
/** Dummy function to allow code to run **/
var serverURL = function() { return ""; }
function _showorderResult(arr) {
// var value1 = arr[0].price;
// var value2 = arr[0].quantity;
var result;
var runningTotal = 0;
for (var i = 0; i < arr.length; i++) {
result = arr[i].price * arr[i].quantity;
runningTotal += result;
$("#itemimage").html("<img src='" + serverURL() + "/images/" + arr[i].imagefile + "' width='200'>");
$("#price").html("Price" + ": " + " $" + arr[i].price);
$("#itemname").html("Item" + ":" + arr[i].itemName);
$("#quantity").html("Quanitiy" + ":" + arr[i].quantity);
$("#result").html("Running" + ":" + runningTotal);
$("#requestedDateTime").html("To delivery by" + ":" + arr[i].requestedDateTime);
$("#deliveredDateTime").html("Delivered on" + ":" + arr[i].deliveredDateTime);
}
}
_showorderResult(order);
</script>
</html>

How to split innherHTML string using Javascript into specific parts after a certain character like a '+' sign

I need to break a string apart after certain characters.
document.getElementById("result").innerHTML = Monster + "<p id='vault" + loop + "'> || HP: " + HP + "</p>" + " || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
function Chest(id){
window.open('LootGen.html', '_blank');
}
function Combat(id){
document.getElementById("C").value = document.getElementById("vault" + id).innerHTML;
}
When this runs the value that results is:
|+HP:+20
However I only want '20' part,now keep in mind that this variable does change and so I need to use substrings to somehow pull that second number after the +. I've seen this done with:
var parameters = location.search.substring(1).split("&");
This doesn't work here for some reason as first of all the var is an innher html.
Could someone please point me in the write direction as I'm not very good at reading docs.
var text = "|+HP:+20";
// Break string into an array of strings and grab last element
var results = text.split('+').pop();
References:
split()
pop()
using a combination of substring and lastIndexOf will allow you to get the substring from the last spot of the occurrence of the "+".
Note the + 1 moves the index to exclude the "+" character. To include it you would need to remove the + 1
function Combat(id){
var vaultInner = document.getElementById("vault" + id).innerHTML;
document.getElementById("C").value = vaultInner.substring(vaultInner.lastIndexOf("+") + 1);
}
the code example using the split would give you an array of stuff separated by the plus
function Combat(id){
//splits into an array
var vaultInner = document.getElementById("vault" + id).innerHTML.split("+");
//returns last element
document.getElementById("C").value = vaultInner[vaultInner.length -1];
}

How do I copy (or even having a button to select it all) a document.getelementbyid output field in html?

I'm trying to essentially set up a button that will either copy a bunch of text that will get output to a document.getelementbyid output to help me out while at work. This is what I have so far for the output and everything works, but would love to have a button that will automatically highlight everything taken from all my input fields.
function display(){
var caller = document.getElementById("form1").value;
var ctn = document.getElementById("form2").value;
var fan = document.getElementById("form3").value;
var business = document.getElementById("form4").value;
var requestor = document.getElementById("form5").value;
var reason = document.getElementById("form6").value;
document.getElementById("output").innerHTML = "form1: " + form1 + "<br>form2: " + form2 + "<br>form3: " + form3 + "<br>form4: " + form4 + "<br>form5: " + form5 + "<br>form6: " + form6;
}
This feeds data from my input fields at the top (naturally they have different names and labels in the document, just can't copy anything proprietary here). The below codes are the button code and the paragraph code to display it when I click so that it appears on the page for me to select.
<button onclick="display();" style="width: 50px; background-color:#3ea055">Submit</button>
<p id="output"></p>
I've tried several different snippets of code online to get it to either select or copy or whatever, and it isn't working.
you dont have variables named form1 form2 etc., in the output area I've changed the values to your variable names try this
function display(){
var caller = document.getElementById("form1").value;
var ctn = document.getElementById("form2").value;
var fan = document.getElementById("form3").value;
var business = document.getElementById("form4").value;
var requestor = document.getElementById("form5").value;
var reason = document.getElementById("form6").value;
document.getElementById("output").innerHTML = "form1: " + caller + "<br>form2: " + ctn + "<br>form3: " + fan + "<br>form4: " + form4 + "<br>form5: " + requestor + "<br>form6: " + form6;
}
In the line where you print the values to the output element you need to use the variables you just filled.
document.getElementById("output").innerHTML = "form1: " + caller + "<br>form2: " + ctn+ "<br>form3: " + fan + "<br>form4: " + business + "<br>form5: " + requestor + "<br>form6: " + reason;

JS Fine in FF, bugged in Chrome

I built a page that uses a simple JSon table and JS/JQ to present that data. Hosted together on one sheet it works fine in both Chrome and FF. Split into seperate HTML, CSS, JS and JSON files, however, there is a slightly variable bug in Chrome.
Page: http://www.lafairclough.co.uk/JTest/index.html
Select two options from the drop down and the charts on the right should show the relative performance data from two cars (top to bottom: 0-60, 0-100, Standing Qtr and Top Speed). These are colour coded with green being the faster result and orange denoting a draw for a given variable.
The charts are made using Java to calculate and set a CSS div width. In Chrome, however, this div width is (sometimes, but often) getting calculated as a much higher figured than expected. As flows:
// Perf. BAR CHART SIZE CSS CAR A
$.getJSON("cars.json", function (data) {
$(document).ready(function () {
$('#dropdown1').change(function () {
var index = parseInt($(this).val()),
html = "<p class=\"barText\">" + " " + data.carList[index].model + " " + data.carList[index].variant + "</p>";
$(".carA060").html(html);
var index = parseInt($(this).val());
var num = data.carList[index].zero60 * 10;
$(".carA060").css('width', num + '%').show();
html = "<p class=\"barText\">" + " " + data.carList[index].model + " " + data.carList[index].variant + "</p>";
$(".carA0100").html(html);
var index = parseInt($(this).val());
var num = data.carList[index].zero100 * 5;
$(".carA0100").css('width', num + '%').show();
html = "<p class=\"barText\">" + " " + data.carList[index].model + " " + data.carList[index].variant + "</p>";
$(".carAsQTR").html(html);
var index = parseInt($(this).val());
var num = data.carList[index].sQTR * 5;
$(".carAsQTR").css('width', num + '%').show();
html = "<p class=\"barText\">" + " " + data.carList[index].model + " " + data.carList[index].variant + "</p>";
$(".carAvMAX").html(html);
var index = parseInt($(this).val());
var num = data.carList[index].vMAX * 0.5;
$(".carAvMAX").css('width', num + '%').show();
});
});
});
Any idea as to why it's going awry in Chrome would be hugely appreciated.
Thanks,
Lee.
your are passing 14.6 ( the mazda ) in your json and multiplying it by 10 for the width so thats why you are
out of bound of container change the logic of the calculation of the width and you will be fine. and the reason why in fire fox its ok and chrome not is because each browser parse the CSS differently . hope this helped

Error when calling JavaScript function — "can't find variable"

I'm attempting to complete and exercise from the JavaScript Bible, and am having trouble getting my script to function.
The assignment is to create a page that allows users to query a planet's name, and, via a script that matches the planet's name with its data stored in the associate arrays, call up its distance and diameter information.
I'm attempting to call the function 'getPlanetInfo' via a button (onclick='getPlanetInfo()'). However, my error console reports that it cannot find a variable named 'getPlanetInfo' when I attempt to run it.
I've attached both my JS and HTML code below. Any idea as to why my function isn't being properly called would be hugely appreciated.
HTML:
<!DOCTYPE html>
<html>
<head>
...
<script type="text/javascript" src="planets.js"></script>
</head>
<body>
<h1>Check a planet's distance from the sun and its diameter!</h1>
<form>
<input type="text" name="entry" id="entry">
<input type="button" value="Check it!" onClick="getPlanetInfo()">
</form>
</body>
</html>
JS:
var planetNames = new Array(4);
planetNames[0] = "Mercury";
planetNames[1] = "Venus";
planetNames[2] = "Earth";
planetNames[3] = "Mars";
var planetDistances = new Array(4);
planetDistances[0] = "36 million miles";
planetDistances[1] = "67 million miles";
planetDistances[2] = "93 million miles";
planetDistances[3] = "141 million miles";
var planetDiameters = new Array(4);
planetDiameters[0] = "3,100 miles";
planetDiameters[1] = "7,700 miles";
planetDiameters[2] = "7,920 miles";
planetDiameters[3] = "4,200 miles";
function getPlanetInfo()
{
var selectedPlanet = document.getElementById("entry").value;
for (var i = 0; i < planetNames.length; i++)
{
if (planetNames[i] == selectedPlanet)
{
break;
}
}
if (i < planetNames.length)
{
alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
}
else
{
alert("Sorry, " + selectedPlanet + " isn't in the database.");
}
}
This line:
alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
is missing a + sign after planetDistances[i], so the function has a syntax error and is not created, and naturally it's not found when called.
http://www.jsfiddle.net helps you create a reproducible case that we can all see, use it when you need to ask js questions.
You're missing a + - this:
alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
should be
alert(selectedPlanet + " is " + planetDistances[i] + " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
You should use something like Firebug to catch syntax errors when loading your script.

Categories