JS: creating user input amount of rows - javascript

I'm new to JavaScript and I'm trying to create user input amount of rows. I know how to do this with document.write but I can't get this to work with innerHTML.
This is what I've got so far:
function myFunction() {
var x = document.getElementById("myText").value;
if ( (x >> 0) > 0 ) {
for ( --- I've tried everything I can think of here but nothing works -- ) {
document.getElementById("secondblock").innerHTML = x + "<br />"
}
This bit:
if ( (x >> 0) > 0 ) {
is for making sure the input is a number -- I'm using the same input field for other (string) functions too. I'm sure there's some better way to check whether my var x is a number or not, but I've just been using this method.
This is what I'm trying to create (if user inputs number 5):
1.
2.
3.
4.
5.

Try this
document.getElementById("secondblock").innerHTML += x + "<br />"
Full example
function myFunction() {
var x = document.getElementById("myText").value;
for(let i = 0; i <= x; i++) {
x.innerHTML += i + "<br />"
}
}
With innerHTML you are resetting the innerHTML every time. So to get the desired output you just need to concat the previous innerHTML as well. Try the code below and you will see the innerHTML resetting to the last insert.
function myFunction() {
var x = document.getElementById("myText").value;
for(let i = 0; i <= x; i++) {
x.innerHTML += i + "<br />"
}
x.innerHTML = 'Tadaaaa'
}

the issue was that you were over-writing the innerHtml instead of appending.
here's an example of how you can change innerHTML whenever the input changes:
<input value="5" id="myText" onchange="myFunction()">
<div id="secondblock"></div>
<script>
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("secondblock").innerHTML = "";
if ( (x >> 0) > 0 ) {
for (let i = 0; i < x; i++) {
document.getElementById("secondblock").innerHTML += (i + 1) + "<br />"
}
}
}
</script>

The problem is you are replacing inputs in for loop everytime. Instead you need to concat every input and then replace with innerHTML. Check below:
function myFunction() {
let value = document.getElementById("myText").value;
let x = parseInt(value)
if (!isNaN(x) && parseInt(x) > 0 ) {
let finalStr = '';
for(let i=1;i<=x;i++){
finalStr += i +'<br />'
}
document.getElementById("secondblock").innerHTML = finalStr;}
}

Does the function get called?
put console.log in first line to check
if it doesn't get called check your html do you have an event attached with the function?
for the function:
function myFunction() {
console.log('do i get called?');
var x = document.getElementById("myText").value;
if ( (x >> 0) > 0 ) {
//get the element
var el = document.getElementById("secondblock");
//clean html for next call
el.innerHTML = '';
for (let i = 1; i <= x; i++) {
// you were overriding second block instead of adding to it
el.innerHTML += i + "<br />"
}
}
}

You can use this below:
function myFunction() {
var x = document.getElementById("myText").value;
if ( isNaN(x) ) {
for ( --- I've tried everything I can think of here but nothing works -- )
{
document.getElementById("secondblock").innerHTML = x + "<br />"
}
}
}
OR
function myFunction() {
var x = document.getElementById("myText").value;
if ( typeof(x) == 'number' ) {
for ( --- I've tried everything I can think of here but nothing works -- )
{
document.getElementById("secondblock").innerHTML = x + "<br />"
}
}
}

Related

Trying to use alert() to show sum of numbers from 1 to whatever number you put in

So the problem here is I need an alert box with my provided code in it to show up. I have tried a lot and it is still not showing what I want it to. I will also provide a picture of what I am looking to re-create.
Here is my code:
function sumOfNumbers() {
var theNumber = document.getElementById("txtNumber").value;
if (theNumber > 0) {
var theSum = 0;
for (var i = 1; i <= theNumber; i++) {
theSum += i;
}
alert(
"The sum of all the numbers from 1 to " + theNumber + " is " + theSum + ""
);
} else {
alert("negative " + theNumber);
}
}
<input type='text' id='txtNumber'>
<input type="button" value='Calculate Sum' onclick="sumOfNumbers()"/>
For some reason, my HTML tags on the top aren't showing. Here is what the box is supposed to look like:
When I click on the "calculate sum" button, nothing will even show. Any help is greatly appreciated!
I've slightly altered your code to use an eventListener rather than an inline click handler. Your code had a few syntax errors (missing closing braces, misplaced else) that were causing the issues. I always find it helpful to use consoleLog when trying to debug, which is how I found those bugs.
let btn = document.querySelector('.btn');
btn.addEventListener('click', sumOfNumbers);
function sumOfNumbers() {
var theNumber = (document.getElementById("txtNumber").value);
if (theNumber > 0) {
var theSum = 0;
for (var i = 1; i <= theNumber; i++) {
theSum += i;
}
alert('The sum of all the numbers from 1 to ' + theNumber + ' is ' + theSum + '');
} else {
alert(`invalid input. ${theNumber} is a negative number`);
}
}
<input type='text' id='txtNumber'>
<button type="button" class="btn">Calculate</button>
You can create an N array using [ ...Array(theNumber).keys() ] and then loop through and add like so
const sumOfNumbers = () => {
const theNumber = document.querySelector("#txtNumber").value;
if(isNaN(theNumber) || (+theNumber < 0))
{
return alert(`Not valid or negative number ${theNumber}`);
}
var numArray = [ ...Array(+theNumber).keys() ];
let sum = 0;
for(let i = 0; i < numArray.length; i++)
{
let num = i + 1;
sum += num;
}
alert(`The sum of all numbers from 1 to ${theNumber} is ${sum}`);
}
<input type='text' id='txtNumber'>
<input type="button" value='Calculate Sum' onclick="sumOfNumbers()"/>

website breaks when running this function

I have the following function:
function Test() {
var x = document.getElementById("input").value;
var res = "";
var c = 1;
var stoc = "";
while (x > 0) {
var help = c.toString();
var h = help.length;
while (h > 0) {
res += help[h - 1];
h--;
}
if (res === help) {
stoc += res + ";" + " ";
x--;
}
c++;
}
document.getElementById("stoc").innerHTML = stoc;
}
Whenever i trigger the function the button stays pushed and the site stops responding. The algorithm is supposed to return the first x polindrom (that are written the same way from right to left ex 121) numbers.
Your browser is crashing because x is never getting decremented causing the loop to never exit. Check the value of help in the debugger.

How to count the number of section tags in an article tag?

I have been trying to write code that would use an embedded for loop to calculate the number of sections inside of each article (there is more than one so I can't use getID) in a document. When the button is clicked the code works but the numbers it calculates are completely off which means something isn't counting correctly. Here is my function:
<script>
function Calculations() {
var a = document.getElementsByTagName("article");
var s = 0;
var z = 0;
var x;
for (x = 0; x < a.length; x++) {
var cn = a[x].childNodes;
z++
for (i = 0; i < cn.length; i++) {
if (cn[i].nodeType == 1) {
if (cn[i].tagName == "P"); {
s++;
}
}
}
alert("Article " + z + " has " + s + " section.")
s = 0
}
alert("There are " + a.length + " total articles.")
}
</script>
Thank you so much for your help!

How to get rid of all double commas

No this isn't a duplicate because all of the answers are different in other posts.
Does anyone know how to get replace something specific in a string? for example I'm trying to get rid of ALL commas that area together. Keep single commas but get rid of two only
For example:
w,h,o,,w,h,a,t,w,h,e,n,w,h,e,r,e,,t,h,e,n,,c,a,n,,b,u,t,,
I want to get rid of all instances where the double commas appear. Something kind of like:
var example = text.replace(/,,/g,' '); /*Space where ' ' is*/
If you understand what I mean. The next step is:
var text.replace(/,/g,'');
Thank you!
Code:
<html>
<head>
<script>
function decrypt() {
var input = document.getElementById("input").value;
var x = input.split(",");
var txtDisp="";
for(var i = 0; i < x.length; i++) {
if(x[i].type = "text") {
crack = 94-(x[i]-32)+32;
toTxt = String.fromCharCode(this, crack);
txtDisp = txtDisp+","+toTxt;
prep = txtDisp.replace(/,,/g,"");
}
document.getElementById("prompt").innerHTML=prep;
}
}
</script>
</head>
<body>
<textarea rows='4' cols='100' style='resize:none;' id='input'></textarea>
<br>
<input type='button' value='execute' onclick='decrypt()' />
<p id='prompt'>
</p>
</body>
</html>
P.s. this code is already posted somewhere else where I asked a question.
Why don't you do:
var text = "61,59,44,47,43,43, ,39,54,37, ,37,47,41,44, ,59,61,48, ,53,48,42,47, ,42,54,57,53,44, ,47,56,42,57,48, ,47,56,56, ,43,61,53,58, ,47,41,44, ,42,39,61,43, ,43,53,48,59,57, ,42,54,57,44,57, ,61,48,58, ,39,47,41,50,58";
example = text.split(",,").join("").split(", ,").join("");
the result is:
"w,h,ow,h,a,t,w,h,e,n,w,h,e,r,et,h,e,nc,a,nb,u,t"
I myself also tried to do it like:
example = text.replace(/,,/g,'').replace(/, ,/g,'');
the result was:
"w,h,ow,h,a,t,w,h,e,n,w,h,e,r,et,h,e,nc,a,nb,u,t"
I changed your code like this:
function decrypt() {
var val = document.getElementById("input").value;
var x = val.split(",");
var txtDisp = "";
for (var i = 0; i < x.length; i++) {
if (!isNaN(parseInt(x[i]))) {
var num = parseInt(x[i]);
crack = 94 - (num - 32) + 32;
toTxt = String.fromCharCode(this, crack);
txtDisp = txtDisp + "," + toTxt;
prep = txtDisp.replace(/,,/g, "").replace(/, ,/g, "");
}
document.getElementById("prompt").innerHTML = prep;
}
}
and it works. check this DEMO out.
Try this:
function decrypt() {
var input = document.getElementById("input").value;
var x = input.split(",");
var txtDisp = "";
for (var i = 0; i < x.length; i++) {
if (x[i] !== ' ') {
crack = 94 - (x[i] - 32) + 32;
toTxt = String.fromCharCode(this, crack);
txtDisp += "," + toTxt;
} else {
txtDisp += " ";
}
}
document.getElementById("prompt").innerHTML = txtDisp.replace(/,/g, "");
}

sending infinity number of checkbox values to text

I have a table with n number of rows with checkboxes and a what i want to do is if i select a checkbox the value should go to the text area, so i stored all elements in an array first, but it isnt happening, as you can see i added alerts as well to check it out. please help.
window.onload = function () {
var oRows = document.getElementById('rnatable').getElementsByTagName('tr');
var iRowCount = oRows.length;
alert('Your table has ' + iRowCount + ' rows.');
var i = 0;
cb = new Array(iRowCount);
while (i <= iRowCount) {
var id = 'check'+ i;
cb[i] = document.getElementById(id);
i++;
}
//alert('Your table has ' + cb[i].value + ' rows.');
for(var a=0; a < iRowCount; a++) {
var fasta = document.getElementById('fasta');
if(cb[a].checked) {
fasta.value = cb.value + ",";
};
};
}
Are you seeing an error in the console? I suspect that when while (i <= iRowCount) runs when i === iRowCount that document.getElementById(id) isn't yielding a result, and that then when you use that value, bad things happen.
Also, each lap through the fasta loop overwrites the previous value. You probably want something like fasta.value += cb.value + ","; instead.

Categories