Text Value From HTML Into Javascript Var? - javascript

I would like to know if the following line is the correct way to take html and put it into a Javascript var as numeric value?
var thePoolHeatingFeeRounded = Number(document.getElementsById("priceDisplayPoolHeating").innerHTML);
Nevermind that the variable name has the word 'rounded' in it. The value that I am trying to put into this var is a 2 point float that has already been rounded and it exist as html.
Below is the line of HTML code that is referenced by getElementsById...
$<div id="priceDisplayPoolHeating" class="priceDisplay">8.00</div>
Any input is greatly appreciated.

Try this instead:
var thePoolHeatingFeeRounded = Number(document.getElementById("priceDisplayPoolHeating").innerHTML);
You were calling getElementsById which is not correct (it is not plural), I changed it to getElementById
Tip: if you need to check whether the Number is valid you can use !isNaN(thePoolHeatingFeeRounded) or use a trick to turn it into a default number (such as 0 or -1) like this:
var thePoolHeatingFeeRounded = Number(document.getElementById("priceDisplayPoolHeating").innerHTML) || 0;
You can also use parseFloat():
var thePoolHeatingFeeRounded = parseFloat(document.getElementById("priceDisplayPoolHeating").innerHTML) || 0;

You are very close. Supposed to be getElementById, not Elements. I created a little code to show you how it works.
Here's what the code looks like in this website's code displayer:
function displayText(){
var thePoolHeatingFeeRounded = Number(document.getElementById("priceDisplayPoolHeating").innerHTML)
alert(thePoolHeatingFeeRounded);
}
<div id="priceDisplayPoolHeating">8.01</div><input type="button" onclick="displayText()" value="Display the innerHTML of Pool Heating">

Related

How can I set attribute which ends with dollar sign using Javascript?

I'm trying to create a pre-processor that converts some custom markup in a file into attribute names which works with Polymer's data binding $= annotation, however I've come across a stumbling block.
I cannot set attributes using Javascript that contain a dollar sign.
I'm trying to convert
<p stuff="align bottom#md top#lg; offset 2gu#md; "></p>
to
<p align-bottom$="{{globals.abovemd}}" align-top$="{{globals.abovelg}}" offset-2gu$="{{globals.abovemd}}">
I have tried:
.setAttribute("align-bottom$", "{{globals.abovemd}}");
But it won't work because the attribute name cannot contain a dollar sign.
Can any one think of a way I can get around this?
This might do the trick(setting invalid attribute names), although obviously not valid in all cases:
function setDollar(el,name,val){
var attrs = [];
var tagName = el.tagName;
for (var i = 0; i < el.attributes.length; i++) {
var attrib = el.attributes[i];
if (attrib.specified) attrs.push(attrib.name+'="'+attrib.value+'"')
}
el.outerHTML = '<'+tagName+ ' '+name+'$="'+val+'"'+attrs.join(' ')+'>'+ el.innerHTML+'</'+el.tagName+'>';
attrs.forEach((attr)=>el.setAttribute(attr.name, attr.value))
}
setDollar(document.querySelector('#wow'),'foo','bar')
<div id="wow"><p>something</p></div>
Still, needs checking for closing tag etc.
Just exclude the $ anytime you are dealing with that property. The $ is just reflecting the property to the attribute onto that DOM element.
.setAttribute("align-bottom", globals.abovemd);
Pretty sure this gonna work
(you need put align-bottom$="" into your html first, this is just to update the value):
.attributes['align-bottom$'].value = "{{globals.abovemd}}";

Javascript - How to get attribute value from a tag, inside a specific div class?

Snippet of HTML code I need to retrieve values from:
<div class="elgg-foot">
<input type="hidden" value="41" name="guid">
<input class="elgg-button elgg-button-submit" type="submit" value="Save">
</div>
I need to get the value 41, which is simple enough with:
var x = document.getElementsByTagName("input")[0];
var y = x.attributes[1].value;
However I need to make sure I'm actually retrieving values from inside "elgg-foot", because there are multiple div classes in the HTML code.
I can get the class like this:
var a = document.getElementsByClassName("elgg-foot")[0];
And then I tried to combine it in various ways with var x, but I don't really know the syntax/logic to do it.
For example:
var full = a.getElementsByTagName("input")[0];
So: Retrieve value 41 from inside unique class elg-foot.
I spent hours googling for this, but couldn't find a solution (partly because I don't know exactly what to search for)
Edit: Thanks for the answers everyone, they all seem to work. I almost had it working myself, just forgot a [0] somewhere in my original code. Appreciate the JQuery as well, never used it before :-)
The easiest way is to use jQuery and use CSS selectors:
$(".elgg-foot") will indeed always get you an element with class "elgg-foot", but if you go one step further, you can use descendent selectors:
$(".elgg-foot input[name='guid']").val()
That ensures that you only get the input named guid that is a child of the element labelled with class elgg-foot.
The equivalent in modern browsers is the native querySelectorAll method:
document.querySelectorAll(".elgg-foot input[name='guid']")
or you can do what you have yourself:
var x = document.getElementsByClassName("elgg-foot")
var y = x.getElementsByTagName("input")[0];
Assuming you know it is always the first input within the div
You can combine it like this:
var a = document.getElementsByClassName("elgg-foot")[0];
var b = a.getElementsByTagName("input")[0];
var attribute = b.attributes[1].value;
console.log(attribute); // print 41
Think of the DOM as the tree that it is. You can get elements from elements in the same way you get from the root (the document).
You can use querySelector like
var x = document.querySelector(".elgg-foot input");
var y = x.value;
query the dom by selector https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
var fourty1 = document.querySelector('.elgg-foot input[name=guid]').value;
querySelector will return the first match from the selector. This selector will find the element with class elgg-foot and then look at the input element inside of that for one named guid and then take the value of the selected element.
I think the simplest way would be using JQuery. But using only javascript,
the simplest way would be:
var div = document.getElementsByClassName("elgg-foot")[0];
var input = div.getElementsByTagName("input")[0];
alert(input.value)
Take a look at this JSFiddle here: http://jsfiddle.net/2oa5evro/

retrieving fontSize from html element

I am trying to animate something.
I set the the default font-size in the html element in css.
I am trying to get the font-size that I set in the css, and then use it in javascript.
I tried this...
var somevariable = getElementById('HtmlId');
var anothervariable = somevariable.style.fontSize;
but I get NAN.
I have tried parsing the variable assuming that it returns a string.
I want to get the css
I recommend you to use jQuery :
var fontSize = parseInt(jQuery('#HtmlId').css('font-size'), 10);
use of pure JavaScript may not return desired result, as if you run following lines separately in console (site:stackoverflow.com). results are different.
document.body.style.fontSize // ''
jQuery('body').css('font-size') // 13px
It should be :-
var somevariable = document.getElementById('HtmlId');
The line after that is fine.
Here is a non-jquery solution...works even if font is not not set in CSS. Kind've clumsy...
var myElem = document.getElementById("myElementId");
var fontSize = document.defaultView.getComputedStyle(myElem, null).fontSize;
edit- someone else saw what the real error probably is... missed "document."
if you're using jquery, you could do it this way:
var somevariable = $("#HtmlId").css("font-size");

Use a variable for the index of an array in javascript

Here is my code:
var span = getSpanWithClass("galleria-current");
var slideNumber = span.innerHTML
var imageIDDivs = document.getElementsByClassName("slideshowImage");
var singleimageidDiv = imageIDDivs[slideNumber]
If I use this, sigleImageidDiv doesn't have anything in it. If I just put 0 or 1 in like this:
var singleimageidDiv = imageIDDivs[1]
It works fine. slideNumber is 1, in my test cases.
I have tried these as well:
var singleimageidDiv = imageIDDivs[Number(slideNumber)]
var singleimageidDiv = imageIDDivs[parseInt(slideNumber)]
What is the proper way to use a variable as the index of an array?
Parse to int with a radix.
This is the proper way of doing it:
imageIDDivs[parseInt(slideNumber, 10)];
Live DEMO
If it doesn't work, then your problem is somewhere else.
BTW indexes work with strings as well.
DEMO
innerHTML returns the string inside the element, so if even if you have a number inside your element, it'll be returned as a string, that's why when you use that variable as an index for your array, you don't get a result.
Using parseInt is an acceptable solution, you could also just do something like span.innerHTML * 1, that would force JS to treat the string as an integer.
I think, you have an error in your getSpanWithClass function.

Javascript debugging - script works with hard coded variable, not with getElementById('id').value

I'm trying to debug some javascript I wrote and can't figure out why it's not working. If I hard code the variables it works fine, but if I use document.getElementById('id').value to get the variable it fails.
The example below works fine but as soon as I un-comment the commented lines it doesn't. Printing the variables before and after the second section they seem to be identical.
Really don't get what's going on. Maybe I just need to sleep on it, but if anyone's got suggestions that would be great!
roof_width = 5;
roof_depth = 3;
panel_width = 2;
panel_depth = 1;
panel_power = 200;
roof_margin = 0.100;
panel_gap = 0.05;
roof_width = document.getElementById('roof_width').value;
roof_depth = document.getElementById('roof_depth').value;
// panel_width = document.getElementById('panel_width').value;
// panel_depth = document.getElementById('panel_depth').value;
panel_power = document.getElementById('panel_power').value;
// roof_margin = document.getElementById('roof_margin').value;
panel_gap = document.getElementById('panel_gap').value;
Are you trying to add numbers that are in text boxes? Because of the way JavaScript's variable typing system works (combined with the overloading of the + operator), 2 + 2 === 4 (adding numbers) but '2' + '2' === '22' (string concatenation). Try changing the lines to, for example:
panel_width = parseFloat(document.getElementById('panel_width').value);
or alternatively:
panel_width = Number(document.getElementById('panel_width').value);
This will ensure that JavaScript treats the numbers as numbers rather than as strings.
JavaScript parameters can't be called in the same way that you're calling HTML elements. In order to call
document.getElementById('roof_margin').value;
you need to assign 'roof_margin' to an HTML form element.
Pherhaps you have multiple dom elements with the same id? Remember the dom element ID must be unique. I suggest you to use jquery for interacting javascript with html.
Make sure your code is in an onload function. Otherwise the elements may not have been loaded into the DOM yet.
window.onload = funciton(){/* code here */};

Categories