JS function that counts up to entered number - javascript

I am trying to make a script that counts up to the entered number in an field in HTML and makes an unordered list of every integer preceding it and also display whether it is even or odd.
I've tried something like this
<script>
const inputEl = document.getElementById("input-el")
let ulEl = document.getElementById("ul-el")
let number = null
inputEl.addEventListener("click", function() {
let number = inputEl.value
console.log(number)
})
function printNumbers(){
for (let i = 0; i <= number; i++){
if (i % 2 === 0){
ulEl.innerHTML += "<li>" + i + ": Even" + "</li>"
console.log(i)
}
else {
ulEl.innerHTML = "<li>" + i + ": Even" + "</li>"
}
}
}
</script>
However the for loop gets stuck on 0, regardless of my input. Tried pushing i into a numbersArray but it always displayed 0

You haven't called the function. So this has to be triggered when the button is clicked right? So you should call the function inside the event listener and pass the input value as an argument,
inputEl.addEventListener("click", function() {
let number = inputEl.value
printNumbers(number);
});
And add the parameter to your function now,
function printNumbers(number){
for (let i = 0; i <= number; i++){
if (i % 2 === 0){
ulEl.innerHTML += "<li>" + i + ": Even" + "</li>"
console.log(i)
}
else {
ulEl.innerHTML = "<li>" + i + ": Even" + "</li>"
}
}
}

Related

How to use the splice and binary search on the data to delete and search

I am trying to the splice method but it is not working properly want to delete one user but it is deleting 2.
Also want to add the binary search button
this is the requirement for binary search
Replace the sequential access algorithm to operate on the arrays with a binary search algorithm.
To implement this, the array’s data must be sorted. You may refer to an online example available at Array.prototype.sort() to learn about sorting data in arrays.
function Display_Athlete() {
var text = "<hr/>";
for (let i = 0; i < athlete_name.length; i++) {
text += "Athlete No - " + (i + 1) + ", Athlete Name is " + athlete_name[i]
+ " and height is " + athlete_height[i] + "<br>";
}
document.getElementById("message").innerHTML = text;
}
//Created function to remove the user
function Remove_Athlete() {
var person = prompt("Enter the name to remove the Athlete");
for (let i = 0; i < athlete_name.length; i++) {
athlete_name.splice(person - 1, 1);
athlete_height.splice(person - 1, 1);
alert(" Athlete_name " + athlete_name + " Athlete_height " + athlete_height + " is removed ");
}
}
//Create the function to find the user
function Find_Athlete() {
var person = prompt("Enter the name to Find the Athlete");
var text = "";
for (let i = 0; i < athlete_name.length; i++) {
if (athlete_name[i] == person) {
text += "Athlete No - " + (i + 1) + ", Athlete Name is " + athlete_name[i]
+ " and height is " + athlete_height[i] + "<br>";
}
}
document.getElementById("message").innerHTML = text;
if (text == "")
alert(`${person} Invalid Athlete name`);
return "";
}
function Binary_Search(){
}

search whether id consists of dynamic value

The script below will loop through and generate 50 records. I have a dynamic value RANKS = "8". How can I check if 8 is exists in id="rankN"?
The value[RANKS] is dynamic from 1-50
var RANKS = "8";
var ranking;
for (var i = 0; i < rankingList.length; i++) {
var a = 1;
ranking = "<div > " +
("<div id=rank" + a + " class='RankCol'>" + rankingList[i].rankNo + "</div>") +
("<div>" + rankingList[i].username + "</div>") +
("<div>" + rankingList[i].winningAmt + "</div>") +
("<div> " + rankingList[i].uCoin + "</div>") +
(" </div>");
};
Expected result:
A
A
B
B
C
B
A
A
B
G
so if my ranking is 8, the text will bold. IF the value is not within 50, then i will do another css. my main problem is how can i check whether the looped' ID contains the id number same as my RANKS(which is 8)
If you want to check in DOM, then simply var exists = $('#rank8').length !== 0.
If you want it to check inside loop:
var ranks = {};
for (var i = 0; i < rankingList.length; i++) {
newRank = 'rank' + i;
if (typeof ranks[newRank] !== 'undefined') {
// skip
continue;
} else {
ranking = '<div id="' + newRank + '" ...';
}
ranks[newRank] = newRank;
}
Try this
rankingDiv.html(rankingList.map((rank,i) => `<div>
<div id="rank${i+1)" class='RankCol'>${rank.rankNo}</div>
<div>${rank.username}</div>
<div>${rank.winningAmt}</div>
<div>${rank.uCoin}</div>
</div>`);
const $myRank = $(`#rank${RANKS}`);
if ($myRank.length===1) myRank.html(`<b>${$myRank.text()}</b>`)
Older sugggestion
$(\`#rank${RANKS}\`).length===1

.innerHTML is showing up as undefined

ok so I understand this is a very basic JS logic but I am trying to replace any document.write() with .innerHTML and I tried it with the code below
function writeTimesTable(num) {
for(let i = 1; i < 10; i++ ) {
let writeString = i + " * " + num + " = ";
writeString = writeString + (i * num);
writeString = writeString + "<br />";
document.write(writeString);
}
}
function newTable() {
for(let i = 1; i <= 10; i++ ) {
let para = document.getElementById("paragraph");
para.innerHTML = writeTimesTable(i)
}
}
I have a div element with the ID of paragraph already. I keep getting undefined when I look at the div#paragraph and the rest of my code outputs under my script tag but not in the div element. What am I doing wrong?
Your function writeTimesTable() needs to return a value. Your writeString string, needs to be concatenated as well, you can do that with += like seen below:
function writeTimesTable(num) {
let writeString = "";
for(let i = 1; i < 10; i++ ) {
writeString += i + " * " + num + " = ";
writeString += writeString + (i * num);
writeString += writeString + "<br />";
}
return writeString
}
Using para.innerHTML = writeTimesTable(i) probably isn't intended, as it will just display the last loop, so you might also want to use += here as well:
para.innerHTML += writeTimesTable(i)
You normally want to avoid document.write because it literally writes out to the document.
I have also taken the liberty of doing the DOM creation off-page during the loop, and just add it to the actual DOM at the end. This means you aren't constantly re-drawing the page while you loop.
This is better than changing your innerHTML = to innerHTML +=, which you would need to do if you wanted to avoid overwriting each previous iteration of the loop.
function writeTimesTable(num) {
for(let i = 1; i < 10; i++ ) {
let writeString = i + " * " + num + " = ";
writeString = writeString + (i * num);
writeString = writeString + "<br />";
return writeString;
}
}
function newTable() {
const inner = document.createElement('div');
for(let i = 1; i <= 10; i++ ) {
const item = document.createElement('div');
item.innerHTML = writeTimesTable(i);
inner.appendChild(item);
}
let para = document.getElementById("paragraph");
para.appendChild(inner);
}
newTable();
<div id="paragraph"></div>
Your newTable() function with the 10 loops is useless. You're doing 10 times the same stuff over a single DOM element.
Don't use document.write...
I'd do it like:
function newTable( num ) {
var HTML = "";
for (var i=1; i <= num; i++) {
HTML += i +" * "+ num +" = "+ (i*num) +"<br>";
}
return HTML; // Return the concatenated HTML
}
document.getElementById("paragraph").innerHTML = newTable(10);
<p id="paragraph">asdasdasd</p>
Or in a super uselessly cryptic ES6 way:
const newTable = n =>
Array(n).fill().map((_,i) =>
`${i+=1} * ${n} = ${i*n}<br>`
).join('');
document.getElementById("paragraph").innerHTML = newTable(10);
<p id="paragraph">asdasdasd</p>

Get Checked count in dynamic check boxes JavaScript

I'm using following code to design my screen dynamically according to the DB data.
function RefillUI(data) {
var html = "";
$.each(data,
function (i, item) {
$('#patientName').html(item.PatientName);
html += "<div class='col-md-3'> <div class='card'><div class='card_header'><h5>" +
item.DrugName +
"</h5></div><div class='card_body'>" +
"<div class='col-md-12'></div><ul class='col-md-6'><li class='bold'>Ref #</li><li class='bold'>" +
item.ReferenceNo +
"</li>" +
"</ul><ul class='col-md-6'><li class='center'>Refills</li><li class='fill'>1</li></ul>" +
"<table class='table table-bordered table-inverse'><tbody><tr><th>Prescriber</th><td>" +
item.PatientName +
"</td>" +
"</tr><tr><th>Last filled</th><td>Nov 14 2014</td></tr><tr><th>Next fill</th><td>Oct 16 2016</td></tr>" +
"<tr><th>Qty</th><td>" +
item.LastRefillQty +
"</td></tr><tr><th>Last Filled Dispensory</th><td>" +
item.LastRefillDispensory +
"</td></tr></tbody></table><form action='' class='cta center bold'>" +
"<label><input name='refill' type='checkbox' value='refill'>Refill</label></form></div></div></div>";
});
$('#refillcards').html(html);
}
Now I want to check how many check boxes are checked when click a button. How can I do this?
I know only answer in pure Javascript:
First, put this declaration at the top:
checkboxes = []; // No `var', it's global
This will initialize the stuff
function
init (n)
{
// n is the number of check boxes
checkboxes[0] = document.getElementById ('some-id');
checkboxes[1] = document.getElementById ('other-id');
// ...
checkboxes[n - 1] = document.getElementById ('different-id');
}
To check selection for a particular check box, do:
function
checkSelect (n)
{
if (n >= checkboxes.length)
{
throw "Index out of bounds: " + n;
}
return checkboxes[n].value;
}
Then, count all of then
function
count ()
{
var ret = 0;
for (var n = 0; n < checkboxes.length; n++)
{
if (checkSelect (n))
{
ret = ret + 1;
}
}
return ret;
}
var n = $( "input:checked" ).length;
you can replace input with a better selector if you want.

Reversing my encrypt method

I created minor encrypt method to convert a small string based on distance between characters, but can't for the life of me figure out how to reverse it without knowing the distance between each character from the initial conversion. See image for example how it works imgur.com/Ine4sBo.png
I've already made the encrypt method here (Javascript):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
var position;
//var oKey = "P";
function encrypt() // Encrypt Fixed
{
var sEncode = ("HI-MOM").split('');
var oKey = "P";
for (var i = 0; i < sEncode.length; i++) {
if (all.indexOf(oKey) < all.indexOf(sEncode[i])) {
position = all.indexOf(sEncode[i]) - all.indexOf(oKey);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
else {
position = all.length - all.indexOf(oKey) + all.indexOf(sEncode[i]);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
}
}
However, it's the decrypt() method that's killing me.
From what I can tell, your encrypt function can be reduced to this:
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function encrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
result += all[(all.indexOf(sEncode[i]) - all.indexOf(oKey) + all.length - 1) % all.length];
oKey = sEncode[i];
}
return result;
}
(I got rid of the if clause by adding all.length either way, and removing it again with the remainder operator if necessary.)
From there, all you need to do is flip the operands (- all.indexOf(oKey) - 1 becomes + all.indexOf(oKey) + 1 (and since we have no more subtractions, adding all.length is no longer necessary)) and reverse the order (so oKey gets assigned the transformed value instead of the original one):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function decrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
oKey = all[(all.indexOf(sEncode[i]) + all.indexOf(oKey) + 1) % all.length];
result += oKey;
}
return result;
}

Categories

Resources