I have the following textarea
<textarea class="form-control" id="projectname"></textarea>
And I want to get its value and concatenate with the value inside this:
<h1 id="team_title"> Team name </h1>
So basically, after writing "china123" in my textarea I would get in my h1 the following = Team name - china123
I have tried the following:
function myFunction() {
var k = document.getElementById('team_title').innerHTML;
var m = document.getElementById('projectname').value;
var x = k.concat(" -" + m);
document.getElementById('team_title').innerHTML = x;
}
And I add it as a oninput attribute on the textarea. But the problem seems to be that after each input it gets the following
Team name - c -ch - chi - chin - china - china1 - china12 - china123
Although my desired output in the h1 tag is:
Team name - china123
Save the original prefix in the data-prefix property of h1
<h1 id="team_title" data-prefix="Team name "> Team name </h1>
Now keep appending value to the data-prefix value
function myFunction() {
var k = document.getElementById('team_title').getAttribute( "data-prefix" ); //observe the change here
var m = document.getElementById('projectname').value;
var x = k.concat(" -" + m);
document.getElementById('team_title').innerHTML = x;
}
You can split the string on the - and then concat them together
var input = k.split('-')[0];
var x = input.concat(" -" + m);
Hope this helps :)
function myFunction() {
var k = document.getElementById('team_title').innerHTML;
var m = document.getElementById('projectname').value;
var input = k.split('-')[0];
var x = input.concat(" -" + m);
document.getElementById('team_title').innerHTML = x;
}
<textarea class="form-control" id="projectname" onkeyup="myFunction()"></textarea>
<h1 id="team_title"> Team name </h1>
you must be calling the function onchange, which means everytime you type the function will concatenate, you have 2 choices:
1. make a button or an event that will concatenate AFTER the whole input.
2. save the h1 value and concatenate with that value unchanged (data-* attribute)
I wouldn't use concat for this.
The value of variable m is already converted as a string. In Javascript you can easily add these strings by using the + line.
function myFunction() {
var k = document.getElementById('team_title').getAttribute( "data-prefix" ); //observe the change here
var m = document.getElementById('projectname').value;
var x = k + ' - ' + m;
document.getElementById('team_title').innerHTML = x;
}
Related
Please, would you be able to explain, why I can't do a loop, if I want to store 'innerHTML' in 'output' variable in the second example?: 'var output = document.getElementById('message').innerHTML;'
var x = 0;
var output = document.getElementById('message');
do {
output.innerHTML = output.innerHTML + x;
x = x + 1;
}
while (x < 6);
------------------------------------------------------------
var x = 0;
var output = document.getElementById('message').innerHTML;
do {
output = output + x;
x = x + 1;
}
while (x < 6);
If you are confused with why you can't add innerHTML to the output in output = output +x, but the first example you can. That is because the first example, the output should store something like[object ...]. So everytime, the output.InnerHTML will keep updating. For the second example, you have already set the output to the innerHTML of message and it has already become a string, not a html. So you can't use innerHTML to change anything. The innerHTML only help to change the value of html` tag and that is why the loop doesn't work.
The loop works
but you can't add something like this
var output = document.getElementById('message').innerHTML;
output = output + x;
enter image description here
I'm working on a project for a computers class, and am new to JavaScript. I keep getting NaN for output, and have looked for answers and haven't found any. (Project is a compound interest calculator and UI design is done.)
I'm not really sure what to try, cause I'm a JS newbie.
var i = getNumber("amountInput");
var c = getNumber("compoundedInput");
var l = getNumber("lengthInput");
var r = getNumber("rateInput");
var rc = r / c;
var cl = c * l;
onEvent("calculateButton", "click", function() {
var rca = 1 + rc;
var p = Math.pow(rca, cl);
var f = i * p;
setText("outputArea", f);
});
Output should be a number, but I am getting NaN.
You need to set all the variables inside the onEvent function, so that you get the values of the inputs after the user clicks the button. You're setting them when the page is first loaded, and the inputs will be empty at that time.
onEvent("calculateButton", "click", function() {
var i = getNumber("amountInput");
var c = getNumber("compoundedInput");
var l = getNumber("lengthInput");
var r = getNumber("rateInput");
var rc = r / c;
var cl = c * l;
var rca = 1 + rc;
var p = Math.pow(rca, cl);
var f = i * p;
setText("outputArea", f);
});
NaN in JS means 'not a number'. (mdn reference)
Usually, you would see NaN when you're trying to convert a non-numeric string to a number, either explicitly (e.g. parseFloat('3')), or implicitly (e.g. the expression 3 * 'a' will implicitly try to convert 'a' to a number). Worth noting, dividing by zero does not give NaN in JS (it gives infinity or -infinity); however, 0/0 also gives NaN.
For your use case, you're expecting getNumber to return a numeric, but it seems like it isn't. Look at your getNumber code (or copy it in your question).
if you want to get number from input in html you cant use getNumber()
<input type="text" id="number" >
<button id="submit">Submit</button>
and for geting the number:
const number = documnet.getElementById('number');
const submitBtn = document.getElementById('submit');
submitBtn.addEventListener('click', () => {
const plusOne = 1 + Number(number.value);
console.log(plusOne)
});
I'm trying to inserting the values of counter into an array called numpay.Unfortunately nothing happens.Where's my mistake?Here's what i tried below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example-1</title>
</head>
<body>
<p id="demo"></p>
<script>
function validateForm() {
var months=(principal+principal*interestrate*0.01)/monthlypayment;
var numpay = new Array(months);
for(var i=0;i<=months-1;i++)
{
numpay.push(i);
text += numpay[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
Fixing existing problems
As others have pointed out, something like this should work:
var months = 12;
var numpay = []; // just as easy
var text = "";
for (var i = 1; i <= months; i++) {
numpay.push(i);
text += numpay[i - 1] + "<br/>";
}
document.getElementById('demo').innerHTML = text;
<p id="demo">(empty)</p>
Enhancing your skills
Although you're combining them in your for-loop, you're doing two separate things here: filling out the months, and creating the text you want to add to the DOM.
There's a lot to be said for one bit of code doing only one thing. You could write a reusable range function which uses more modern JS techniques to give you a numeric integer range between two values. So
const range = (lo, hi) => [...new Array(hi - lo + 1)].map((_, i) => i + lo);
Using that, you can create your months variable by calling this function:
const months = range(1, 12);
Then, with this array, you can use Array.prototype.join to combine the values into the text you would like:
const text = months.join('<br/>')
And that leads to a nicer bit of code:
const range = (lo, hi) => [...new Array(hi - lo + 1)].map((_, i) => i + lo);
const months = range(1, 12);
document.getElementById('demo').innerHTML = months.join('<br/>');
<p id="demo">(empty)</p>
If you need that text variable for something additional, then just assign it as the result of the join, and then assign the innerHTML to it.
Obviously that range function is unnecessary. You could just write const months = [...new Array(12)].map((_, i) => i + 1);. But thinking in terms of such abstractions often lets you write cleaner code.
1.) By creating an array like that (new Array(12)) you are saying to create 12 undefined entries in the array. Then you are pushing to the end of the array.
2.) You also need to initialize text with months var months = 12, text;.
var months = 12, text;
var numpay = new Array(months);
for(var i=1; i<=months; i++){
numpay[i] = i;
text += numpay[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
This will still give you undefined at index 0 but I will leave that for you to work out. But doing numpay[i] = i will overwrite your undefined that was created with the array.
Arrays in JS are zero-based, so if you do .push(i) with i === 1, the value 1 goes into the slot for numpay[0].
And then to access that item, you must use numpay[i-1].
Another thing is that you seem to have forgotten to declare and initialize text before the loop starts. You need to do that, if not then the variable only exists inside the loop body (and loses its value each time the loop body ends).
Demo:
var months = 12;
var numpay = []; // just as easy
var text = "- ";
for (var i = 1; i <= months; i++) {
numpay.push(i);
text += numpay[i - 1] + " - ";
}
console.log(text);
When you instantiate an array with a parameter like this:
var numpay = Array(12);
it results in an array with 12 undefined elements. When you push a new item, it will be placed in the 13th slot.
Instead, just do this:
var text = "";
var months=12;
var numpay = [];
for(var i=1;i<=months;i++)
{
numpay.push(i);
text += numpay[i-1] + "<br>"; //use i-1 here, not i
}
document.getElementById("demo").innerHTML = text;
The result is:
"1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>11<br>12<br>"
I am new to Javascript and am trying to create a form that computes a result using a specific equation. I was trying to make var x the baseprice number that the user inputs and then subsequently use that var in an equation. I am wondering if my problem is that I am missing submit input and then have x register on entry somehow? This is what I have so far:
<input type="number" id="baseprice">
<br><br>
Result:
<p id="LESResult"></p>
<script>
var x = document.getElementById("baseprice").value;
var y = 100;
var d = 30;
var z = (x)/(y-d);
var m = z * y;
var num = m;
var n = num.toFixed(2);
document.getElementById("LESResult").innerHTML = n;
</script>
You can add a button and attach an event listener to it like this:
<input type="number" id="baseprice">
<button onclick="calculate_result()">submit</button>
<br><br>
Result:
<p id="LESResult"></p>
<script>
calculate_result = function() {
var x = document.getElementById("baseprice").value;
var y = 100;
var d = 30;
var z = (x)/(y-d);
var m = z * y;
var num = m;
var n = num.toFixed(2);
document.getElementById("LESResult").innerHTML = n;
}
</script>
The problem is that your code runs once, immediately when the page loads. You need to trigger that code in response to something the user does. There is an event called an "input" event that is triggered by the user editing an input. Bind an event handler to your input as follows:
document.getElementById("baseprice").addEventListener("input", function () {
var x = this.value;
var y = 100;
var d = 30;
var z = (x) / (y - d);
var m = z * y;
var num = m;
var n = num.toFixed(2);
document.getElementById("LESResult").innerHTML = n;
});
Note that the first line of the function uses this.value rather than calling .getElementById() - within the event handling function this is a reference to the input element, so you don't need to call .getElementById() again.
Demo: http://jsfiddle.net/8rq7ab71/
Other options would include binding to the "change" or "blur" events, both of which would be triggered only when the user tabs or clicks out of the input when they've finished editing, or adding a "Calculate" button and putting a "click" handler on it. See also: the addEventListener() method.
was hoping if anyone could help. I would like to be able to have it that whenever the arrays I pass into the function change it will display these values in a paragraph tag.
At the moment it doesn't rewrite it and I want it to display like it's steps (i.e 1. ... 2. ...) but it doesn't update the step number or take a new line either. This function is called in another function.
The code so far is:
//javascript code
//cred & grade are arrays
function breakdown(cred, grade){
var change = document.getElementById('bdown'); //'bdown' is the id of the <p>
var to;
var a = 1;
var x = 0;
for(var b = 0; b<cred.length; b++){
//alert(a)
to += a + ". (" + cred[b] + " x " + grade[b] + ")" + "<br /"; //show the step number and the values then take a new line
a++; //increment the step number
change.innerHTML=bdown.innerHTML.replace(change.textContent,to ); //wish to change <p>
}
}
//html code
// the paragraph wish to change
<div id="how"; style="color:white;display: none">
<p id="bdown"></p>
</div>
Using code:
var to = "";
for(var b = 0; b<cred.length; b++){
to += "(" + grade[b] + " x " + cred[b] + ") + ";}
... .getElementById('').innerHTML = to;
Expecting output with cred = [10, 20], grade = [11, 21]:
(10 x 11) + (20 x 21) <-- this expands when arrays have values added to them.
Actual output:
(undefined) <-- doesn't change
I don't have jquery running on my coding platform so javascript code would be really great :)
To do a list of numbered steps, you want to use the ol tag.
Obviously, you'll want to populate the ol tag with li tags :P
Have you tried a simplified version to see if it works? Something like this:
document.getElementById("bdown").innerHTML=to;