JavaScript getElementByID any short method to do same work? [duplicate] - javascript

This question already has answers here:
Javascript Shorthand for getElementById
(23 answers)
Closed 8 years ago.
My below code is working fine, but I want to know, is there any short method of doing same work only by JavaScript?
<lable for="fstValue"></lable> First number is: <input type="text" id="fstValue" value="" />
<lable for="sndValue"></lable> Second number is: <input type="text" id="sndValue" value="" />
<hr>
<div id="showResult1"></div>
<div id="showResult2"></div>
<div id="showResult3"></div>
<div id="showResult4"></div>
<button onclick="sandeep()">Check Result</button>
// Get the value, calculate and show the value
function sandeep(){
// Define local function - sandeep varriable
var a, b, resPlus, resMinus, resMultiple, resDivide;
// Get First & Second value
a = parseInt(document.getElementById("fstValue").value);
b = parseInt(document.getElementById("sndValue").value);
// Do calculation
resPlus = a + b;
resMinus = a - b;
resMultiple = a * b;
resDivide = a % b;
// Show result
document.getElementById("showResult1").innerHTML="Plus is " + resPlus;
document.getElementById("showResult2").innerHTML="Minus is " + resMinus;
document.getElementById("showResult3").innerHTML="Multiple is " + resMultiple;
document.getElementById("showResult4").innerHTML="Divide is " + resDivide;
}

Can certainly array-drive this. Note my sue of parseInt(*, 10), this is important.
var a = parseInt(document.getElementById("fstValue").value, 10);
var b = parseInt(document.getElementById("sndValue").value, 10);
var texts = ["Plus", "Minus", "Multiple", "Divide"];
var results = [a + b, a - b, a * b, a / b];
for(var i = 0; i < 4; i++ ) {
document.getElementById("showResult" + (i+1) + ").innerHTML=" texts[i] + " is " + results[i];
}
Note you're discovering the problem that frameworks like Angular.js and everything else are attempting to solve. Note the following is pseudo code. It sure would be better if you had a snippet of HTML template
<p>{text} is {result}</p>
And you could put this in a loop
{{iterate over results object}}
<p>{result.text} is {result.results}</p>
{{ end iterate}}
Now far less work has to happen in Javascript. But more importantly, work that should happen in HTML now happens in HTML (data layout), and what happens in JS should happen in JS (getting data). That's the state-of-the-art theory.

You can make your own functions at least:
function getElement(id)
{
return document.getElementById(id);
}
And now you can use just getElement("showResult1");
Also you can do the same for innerHtml and other stuff that you repeat in your code.

Related

I'm comparing two variables in an IF statement but I'm getting wrong results [duplicate]

This question already has answers here:
javascript comparison of strings
(4 answers)
Closed 1 year ago.
I tried this code and when running for the first time i clicked start and i got me the result "1 is smaller than 2" whick is right but after changing the first input to 10 and clicking start again, it still showed "10 is smaller than 2". Am I doing something wrong here?
<textarea type="number" id="one">1</textarea>
<textarea type="number" id="two">2</textarea>
Start
<p id="demo"></p>
<script>
function start() {
var numberOne = document.getElementById('one').value;
var numberTwo = document.getElementById('two').value;
if(numberOne>=numberTwo) {
document.getElementById('demo').innerHTML = numberOne + ' is bigger than ' + numberTwo;
}
else {
document.getElementById('demo').innerHTML = numberOne + ' is smaller than ' + numberTwo;
}
}
</script>
You are comparing strings, not numbers.
use parseInt or parseFloat to convert it to a number.
var numberOne = parseFloat(document.getElementById('one').value);
Yes it is expected, input in DOM always string even if the type is number.
parse them to number first before comparing.
const intOne = parseInt(numberOne, 10);
const intTwo = parseInt(numberTwo, 10);
// compare them
if (intOne >= intTwo) {
// do your thing
}
Edit: Update code by #Sebastian Simon suggestion

My if and else statement always think it's -and [duplicate]

This question already has answers here:
IF Statement Always True
(3 answers)
Closed 4 years ago.
I have a selector on my page that has -and or -or. I'd like to change the content of a div depending on what users choose with -And or -Or.
My if and else statements aren't working right now, well it's almost working it just always add -And. It looks as if it always see's -And?
First time I'm trying to use an if and else statement and I think I made mistake.
<script>
function Andor' + count + '(selTag) {
var x = selTag.options[selTag.selectedIndex].text;
if (x = '-and'){
document.getElementById("and-or-' + count + '").innerHTML = " " + x + " ";
} else {
document.getElementById("and-or-' + count + '").innerHTML = " " + x + " (";
}
}
</script>
You use one =, which is 'assign'. You want === (or ==) for 'equals'.
You do the same as: var example = 'foo';. You set the value to a string ('-and'), which always results in true, which makes it look like it's true.
What you want is example=='foo' to check if the content of example equals 'foo'.
Suggested reading material: https://codeburst.io/javascript-double-equals-vs-triple-equals-61d4ce5a121a

Loop through attributes but only output certain ones - javascript

I dont know much of js but I have a code that with a little modification, will do exactly what I want. So here is a part of it that Im stuck. I have some visual objects that have several attributes, most of these attributes are needed for drawing them on the map so I cant just comment them out. I also have a function that prints all the attributes of the object on("mouseover"). I want it to only display the attributes I want, not all.
.on("mouseover", function(d) {
var out = "";
out += d.name + "<br /><br />";
for (v in d) {
out += (!Number.isNaN(Number(d[v])) ? v + ": " + Number(d[v]) + "<br />" : "");
}
document.getElementById("detail").innerHTML = out;
}
I understand what this code does, but what is the most elegant way to constraint the for loop or the out to only include the attributes I want?
The current outcome
obj name
attrIwant1: value
attrIwant2: value
attrIwant3: value
attrIwant4: value
w: blah
x: blah
y: blah
z: blah
I only want to display up until w:blah.
Put the attributes you care about in a set, then when you loop, see if d[v] belongs to the set.
const set1 = new Set(['attrIWant1', 'attrIWant2']); // add the attributes here
for (v in d) {
if (set1.has(d[v])) {
// this is one we care about
}
}
Read more about sets here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
If you always expect the same number of attributes, you can terminate the loop early when out has a certain number of <br />'s in it.
In your example you want to stop when you have 4 attributes, so you would terminate the loop when out contains 6 <br />'s. Your new for loop would be this:
for (v in d) {
out += (!Number.isNaN(Number(d[v])) ? v + ": " + Number(d[v]) + "<br />" : "");
if (out.match(/<br \/>/g).length === 6) break;
}
It is not "elegant", but it's probably the best you'll get without telling me what d is :^)

New to javascript, how to assign an input value to a submit button?

I'm new to javascript and need help with a piece of my code. I am suppose to create a text box that a user can input a number and the function will then roll that many dice. I also need to set limits so a user can't enter -10 or 100 because it is only 1-6. So it looks like this:
var theInput = document.getElementById('num').value;
theInput = parseInt(theInput);
if (theInput < 1) {
theInput="1";
}
else if (theInput > 6) {
theInput = "6";
}
The part I'm stuck on is how I am suppose to link a text box to this piece of code that will then run through my function for dice rolling.
<script type="text/javascript">
function SelectImage6() {
document.getElementById('outputDiv').innerHTML ='';
for(i=0; i<6; i++){
roll2 = Math.floor(Math.random() * 6) + 1;
imgName2 = '../images/die' + roll2 + '.gif';
document.getElementById('outputDiv').innerHTML +=
'<img alt="die image" src="' + imgName2+'" />';
}
}
</script>
<body>
<div style="text-align:center">
<input type="button" value="Click to Roll" onclick="SelectImage6();">
<p id="outputDiv">
<img id="dieImg2" alt="die image"
src="../images/die2.gif" >
</p>
</div>
Where do I assign the var theInput within my code? Any help would be greatly appreciated. Thanks!
Well first you should create the textbox in the html like this:
<input type="text" id="num">
Then have people push a button to start your javascript code. So use the button you already have. Then when the SelectImage6() function is called on the button click, you just put the top javascript code (the one checking the input) into the function SelectImage6() and you will have a nice function that does it all.
To answer the specifics of your question, it makes most sense to get the number of dice to roll inside the SelectImage6 function. To make things nice and clean, you might want to encapsulate that functionality:
// returns the number of dice the user entered. if the user entered a non-numeric
// value, this function will throw an exception. if the user entered less than
// one, the value will be clamped to 1, and if the user entered more than six, the
// value will be clamped to 6.
function getNumDice() {
'use strict';
var numEntered = parseInt( document.getElementById('num').value );
if( isNaN( numEntered ) ) throw 'The number of dice must be numeric.';
if( numEntered < 1 ) numEntered = 1;
if( numEntered > 6 ) numEntered = 6;
return numEntered;
}
I cleaned up your function a little bit. "theInput" is a bit vague for a variable name, so I changed it to something more descriptive. I handled the case where the user doesn't enter a number, and I consolidated the document.getElementById and the parseInt into one line. Also, you were mixing types in your original code. You use parseInt (which returns a numeric type), but then you would set theInput to a string. This may not result in an error thanks to JavaScript's flexible type coercion, but it's bad practice regardless.
Now that you have that function, you can modify your SelectImage6 accordingly:
function SelectImage6() {
'use strict';
var div = document.getElementById('outputDiv'); // cached for efficiency
var html = '';
var roll2, imgName2;
var numDice = getNumDice();
for( i=0; i<numDice; i++ ){
roll2 = Math.floor(Math.random() * 6) + 1;
imgName2 = '../images/die' + roll2 + '.gif';
html += '<img alt="die image" src="' + imgName2+'" alt="die" />';
}
div.innerHtml = html;
}
For SelectImage6, I made some changes (in addition to using the value returned by getNumDice). First, you're repeatedly calling getElementById (once, unnecessarily, at the top of the function, then once for every dice rolled!). Any DOM access is expensive, and if you can avoid doing it multiple times, you should. Secondly, you're repeatedly modifying the innerHtml property which, depending on the complexity of your HTML, and your network latency, could cause flicker or other unpleasant effects. What I chose to do instead was to build up the string first, then set it all at once.
In your original function, you were unwittingly using global variables (implied globals) because you didn't declare roll2 and imgName2 as variables. I fixed that, and added use strict to your functions so this mistake will be caught in the future! (My advice is to always set use strict.);
I hope this helps! Welcome to the world of JavaScript.

JavaScript Calculation Problem - NaN message

I'm calculating a total number. I get the sum values from div's. But in total, instead of numbers I get (NaN - Not a Number)
JavaScript Function:
<script type="text/javascript">
function calculateTotal(){
var total = document.getElementById('valor1').innerHTML*1 + document.getElementById('valor2').innerHTML*1 + document.getElementById('valor3').innerHTML*1 + document.getElementById('valor4').innerHTML*1 + document.getElementById('valor5').innerHTML*1 + document.getElementById('valor6').innerHTML*1;
document.getElementById('total').innerHTML = total;
}
</script>
EDIT:
I found the error, I had a closing tag inside the DIV's like this:
<center><div id="valor1"></center></div>
Changed to:
<center><div id="valor1"></div></center>
You cannot use document.getElementById('valor1').innerHTML directly. You have to convert this to number. Please try this.
var value = document.getElementById('valor1').innerHTML;
var number = parseFloat(value)||0;
Do this for each div innerHTML which have number.
var number = parseFloat(value)||0;
The above line will help you to assign 0 to value if div is empty or div html cannot be converted to a number.
Use parseFloat(document.getElementById('x').innerHTML) to convert them to numbers before performing operations:
var total = parseFloat(document.getElementById('x1').innerHTML) + parseFloat(document.getElementById('x2').innerHTML);
You also may want to check them if they're numeric, here's a simple test using isNaN:
alert((isNaN("23"))?'not number':'number');
HTML:
<div id="valor1">2</div>
<div id="valor2">2</div>
<div id="valor3">ccccc</div>
<div id="valor4">2</div>
<div id="valor5">2</div>
<div id="valor6">2</div>
<hr/>
<div id="total">0</div>
JavaScript:
function $(id) { return document.getElementById(id); }
function get(elem) { return parseFloat($(elem).innerHTML) || 0; }
(function() {
var total =
get('valor1') * 1 + get('valor2') * 1 + get('valor3') * 1 +
get('valor4') * 1 + get('valor5') * 1 + get('valor6') * 1;
$('total').innerHTML = total;
}());
A little optimization of the work and demo.
But why stop here? :) we can make it even better ( I think ):
function get(elem) {
return (parseFloat($(elem).innerHTML) || (function() {
$(elem).innerHTML += " <i>Not a number assumed 0</i>";
return 0;
}()));
}
And the updated demo.
Edit: no errors on Chrome & Mozilla (Linux).
try using parseInt() as in
var total = parseInt(document.getElementById('valor1').innerHTML)*1 + parseInt(document.getElementById('valor2').innerHTML)*1 + ... ;
etc etc
this will ensure that what you're getting out of the fields is in fact, a number
Did you try to put these parts into brackets?
(document.getElementById('valor1').innerHTML * 1) + ...
See: http://rx4ajax-jscore.com/ecmacore/operator/predence.html
Even better - use the parseInt(var string) function;
parseInt(document.getElementById('valor1').innerHTML) + ...

Categories

Resources