Removing commas from arrays in HTML [element.innerHTML] - javascript

So I'm having an issue with this. I'm trying to get rid of those commas. Used varArray.join(" ") too, but with no success. I went as far as creating a for loop, but it didn't work(well it might've worked, but I'm a beginner, though I doubt that).
Here's the code:
let varArray = [];
let rufus1 = document.getElementById('rufus1');
let rufus2 = document.getElementById('rufus2'); // variables for easing syntax
function arrayGiver() {
varArray.push('<div>' + document.getElementById('rufus1').value + '</div>');
// I've used `<div>` instead of `<br>` for line breaking the elements, but when I'll be making bigger more complex projects I should probably use `<br>` shouldn't I?
rufus2.innerHTML = ("You have just added to your collection:" + "<br/>" +
varArray);
//this cleans the input after executing the function
rufus1.value = '';
}
//this makes the function execute on an enter key press
document.addEventListener('keydown', function(enterKey) {
if (enterKey.keyCode === 13) {
arrayGiver();
}
})
<input id="rufus1">
<br>
<br>
<button onclick="arrayGiver();">Bleh</button>
<p id="rufus2"></p>

Because array auto add commas as separator when converted to string. You can get rid of this by simply use join(' ') on varArray as below
let varArray = [];
let rufus1 = document.getElementById('rufus1');
let rufus2 = document.getElementById('rufus2');
// variables for easing syntax
function arrayGiver() {
varArray.push('<div>' + document.getElementById('rufus1').value + '</div>') // I've used `<div>` instead of `<br>` for line breaking the elements, but when I'll be making bigger more complex projects I should probably use `<br>` shouldn't I?
rufus2.innerHTML = ("You have just added to your collection:" + "<br/>" +
varArray.join(' '));
//this cleans the input after executing the function
rufus1.value = '';
}
//this makes the function execute on an enter key press
document.addEventListener('keydown', function (enterKey) {
if (enterKey.keyCode === 13) {
arrayGiver();
}
})
<input id="rufus1" type="text">
<br>
<br>
<button onclick="arrayGiver();">Bleh</button>
<p id="rufus2"></p>

You can use forEach() or another loop to add the array elements to innerHTML
For this answer I used:
varArray.forEach(e => rufus2.innerHTML += e);
which iterates over the array adding each element (e) to rufus2.innerHTML.
let varArray = [];
let rufus1 = document.getElementById('rufus1');
let rufus2 = document.getElementById('rufus2'); // variables for easing syntax
function arrayGiver() {
varArray.push('<div>' + document.getElementById('rufus1').value + '</div>');
// I've used `<div>` instead of `<br>` for line breaking the elements, but when I'll be making bigger more complex projects I should probably use `<br>` shouldn't I?
rufus2.innerHTML = ("You have just added to your collection:" + "<br/>");
varArray.forEach(e => rufus2.innerHTML += e);
//this cleans the input after executing the function
rufus1.value = '';
}
//this makes the function execute on an enter key press
document.addEventListener('keydown', function(enterKey) {
if (enterKey.keyCode === 13) {
arrayGiver();
}
})
<input id="rufus1">
<br>
<br>
<button onclick="arrayGiver();">Bleh</button>
<p id="rufus2"></p>

To achieve expected result, use string variable instead of array as below
let varArray = [];
var list ='';
let rufus1 = document.getElementById('rufus1');
let rufus2 = document.getElementById('rufus2');
// variables for easing syntax
function arrayGiver(){
list = list + '<div>' + document.getElementById('rufus1').value + '</div>'
rufus2.innerHTML = ("You have just added to your collection:" + "<br/>" + list);
list.value = '';
}
https://codepen.io/nagasai/pen/bvQKbX
let varArray = [];
var list ='';
let rufus1 = document.getElementById('rufus1');
let rufus2 = document.getElementById('rufus2');
// variables for easing syntax
function arrayGiver(){
list = list + '<div>' + document.getElementById('rufus1').value + '</div>'
rufus2.innerHTML = ("You have just added to your collection:" + "<br/>" + list);
list.value = '';
}
document.addEventListener('keydown', function(enterKey) {
if(enterKey.keyCode === 13){
arrayGiver();
}
})
body {
font-family: Arial;
font-size: 24px;
}
button {
width: 100px;
height: 25px;
}
<input id="rufus1">
<br>
<br>
<button onclick="arrayGiver();">Bleh</button>
<p id="rufus2"></p>

Related

How can I create a reset button for this game?

I have my current code posted, I'm trying to create a reset button. A button has already been created in my HTML, and I'm grabbing it at the bottom, and adding an event listener, which isn't working for some reason, also trying to figure out the correct code to add it for my game resets when the button is clicked. However having a difficult time with the syntax.
// Array of words
const words = ['planet', 'stars', 'astroid', 'moon', 'satilite', 'orbit', 'universe', 'umbra', 'lunar', 'space', 'astronomy', 'eclipse', 'nebula', 'mars', 'meteorite']
// guesses Array
let myGuesses = []
//variables
let wordSpace = ' - '
let guess = ' '
let space; //number of spaces in word
//score
let tries = 10
let counter ;
//Get random word
let index = Math.floor(Math.random()* words.length)
//play function
function play() {
let userInput = prompt(`would you like to play spaceman? (Y/N)`, "Y")
console.log(words[index])
for(let i = 0; i < words[index].length; i++){
console.log(words[0][i])
let div = document.createElement('div')
div.classList.add('letters')
div.innerHTML=' - '//words[0][i]
document.querySelector('.word-space').append(div)
}
}
//handle click function, inactivates buttons, and changes color to grey; once clicked
let handleclick = e => {
e.target.removeEventListener('click', handleclick)
e.target.style.backgroundColor= 'grey'
console.log(e.target.innerHTML)
myGuesses.push(e.target.innerHTML)
console.log(myGuesses)
console.log(words[index].includes(e.target.innerHTML))
if(words[index].includes(e.target.innerHTML)){
document.querySelector('.word-space').innerHTML= ' '
// let correct = document.createElement('ul')
for(let i = 0; i < words[index].length; i++){
// correct.setAttribute('id','correctLetters' )
// let guess= document.createElement('li')
// guess.setAttribute('class','guess')
console.log(words[0][i])
let div = document.createElement('div')
div.classList.add('letter')
if (myGuesses.includes(words[index][i])){
div.innerHTML = words[index][i]
} else {
div.innerHTML = ' - '
}
document.querySelector('.word-space').append(div)
}
getNumOfTries()
} else {
tries --
getNumOfTries()
}
}
function ans () {
const buttons = document.querySelectorAll('.letter')
buttons.forEach(letter => letter.addEventListener('click',handleclick))
}
ans()
function getNumOfTries (){
console.log(tries)
const showTries = document.querySelector('#myTries')
showTries.innerHTML = ' You have ' + tries + ' tries'
if(tries < 1){
setTimeout(() =>{prompt(`Would you like to try again? (Y,N)`, 'Y')
showTries.innerHTML = 'You loose!'
},2000)
}
// if(tries > 0 && words[index].length === myGuesses.length) {
if(tries > 0 && Array.from(document.querySelectorAll('.letters')).every(letter => letter.innerHTML !== ' - ')) {
// showTries.innerHTML = 'You Win!'
setTimeout(() =>{alert(`You Win!`)
showTries.innerHTML = 'You Win!'
},1000)
}
}
//reset game
let tryAgain = document.querySelector('.Try-Again')
tryAgain.addEventListener('clcik', play)
prevent
div.innerHTML=' - '//words[0][i]
document.querySelector('.word-space').append(div)
play()
You've got a typo there :)
tryAgain.addEventListener('clcik', play)
some notes to the written code:
you don't need to reference the element, if you're not going to use it elsewhere, just do:
document.querySelector('.Try-Again')?.addEventListener('click', play);
i'm not sure about what the "prevent" should do here
you haven't defined a global reference to a "div" parameter that you want to use at:
div.innerHTML=' - '//words[0][i]
use semicolon ';' by the end of each executed code for better code clarity + checkout some coding standards
use code editors like Visual Studio code or other tools - they usually have some basic code formatter (learn they shortcuts, it will optimize your coding process) + other usefull features like clicking through defined param references etc.

Can't add together two variables which store an offsetHeight

I'm trying to add two numbers together so I can use a CSS calc function to reduce the top margin of an element so it shows just the title and its top line text.
var roomInfoPanel = document.querySelector(".room-info");
var panelCapacityInfo = parseInt(document.querySelector(".room-info__capacity").offsetHeight);
var panelTitleRoom = parseInt(document.querySelector(".room-info__title").offsetHeight);
var panelCombinedHeights = panelCapacityInfo + panelTitleRoom;
if (panelTitleRoom && panelCapacityInfo) {
document.querySelector(".room-info").style.marginTop = "calc( -" + panelCombinedHeights + "-7vw + -20px)";
}
However, panelCombinedHeights always returns undefined :(
I don't think this is a scope issue.
The parseInt was added after looking at this article, but without this no good either.
What am I doing wrong?
Try to convert variables to numbers
var roomInfoPanel = document.querySelector(".room-info");
var panelCapacityInfo = parseInt(document.querySelector(".room-info__capacity").offsetHeight);
var panelTitleRoom = parseInt(document.querySelector(".room-info__title").offsetHeight);
// Convert variables to numbers
// Print what to summ
console.log(panelCapacityInfo, panelTitleRoom)
var panelCombinedHeights = Number(panelCapacityInfo) + Number(panelTitleRoom);
// Print summ
console.log(panelCombinedHeights)
if (panelTitleRoom && panelCapacityInfo) {
console.log("Style to be applied:", "calc( -" + panelCombinedHeights + "-7vw + -20px)");
document.querySelector(".room-info").style.marginTop = "calc( -" + panelCombinedHeights + "-7vw + -20px)";
}
.room-info {
height: 200px;
}
.room-info__capacity {
height: 100px;
}
.room-info__title {
height: 70px;
}
<div class="room-info">
<div class="room-info__capacity">
1
</div>
<div class="room-info__title">
2
</div>
</div>
The function offsetHeigth already returns a number, so you don't need the parseInt() here.
Are the values panelCapacityInfo and panelTitleRoom defined or not?
If they are undefined then the error is probably in the querySelector.
var roomInfoPanel = document.querySelector(".room-info");
var panelCapacityInfo = parseInt(document.querySelector(".room-info__capacity").offsetHeight);
var panelTitleRoom = parseInt(document.querySelector(".room-info__title").offsetHeight);
var panelCombinedHeights = parseInt(panelCapacityInfo) + parseInt(panelCapacityInfo)
if (panelTitleRoom && panelCapacityInfo) {
document.querySelector(".room-info").style.marginTop = "calc( -" + panelCombinedHeights + "-7vw + -20px)";
}

i am trying to make a function that check for errors, but i get only one or two errors which is wrong

var checkErrors = 0;
// Check for mistakes function
function yourResult() {
let checkErrors = 0;
let textEnterd = testArea.value;
let orginTextMatch = originText.substring(0, textEnterd.length);
if (textEnterd.length == originText.length || textEnterd == originText) {
if (textEnterd != orginTextMatch) {
++checkErrors;
}
theResult.innerHTML **strong text** = "You did " + checkErrors + " mistakes.";
}
}
testArea.addEventListener('keyup', function() {
yourResult();
}, false);
// "return"
This is a test typing project, i am stuck at the yourResult function, i cant get the desire errors.
The main mistake is that the error count is reset after each stroke.
So put that outside and you can match the characters as they're typed.
It's not far off, so you can try this instead:
// Put check errors variable outside of the function to keep count between the key strokes
// Reset to 0 when starting the test over
let checkErrors = 0;
function yourResult(){
let textEnterd = testArea.value;
let charPos = textEnterd.length;
// Match the characters at their positions. If they don't match, add them up
if (charPos > 0 && textEnterd.charAt(charPos) != originText.charAt(charPos)) {
++checkErrors;
}
theResult.innerHTML = "You did " + checkErrors + " mistakes.";
}

Javascript indexOf and replace - am I missing something

I have this javascript function;
i send it a number from a button and all go well untill the index-of method it has a problem.
CODE:
<script lang="ja" type="text/javascript">
function YellowChair(NumId)
{
if (document.getElementById("CheckBox" + NumId).checked)
{
document.getElementById("ChairImg" + NumId).src = "Images/YellowChair.png";
TypeTheNum(NumId, true);
}
else
{
document.getElementById("ChairImg" + NumId).src = "Images/BlueChair.png";
TypeTheNum(NumId, false);
}
}
function TypeTheNum(NumId,Add)
{
var Label = document.getElementById("SelectedSitsLabel");
var Hidden = document.getElementById("SelectedSitsHidden");
if (Label.innerHTML == "")
{
Label.textContent += NumId;
Hidden.textContent += NumId;
}
else
{
if (Add)
{
Label.textContent += "," + NumId;
}
else
{
// getting stuck here.
if (Label.indexOf((NumId + ",").toString()) != -1)
{
alert("1");
Label.replace((NumId + ",").toString(), "");
}
else
{
alert("ELSE");
Label.replace(("," + NumId).toString(), "");
}
}
}
Hidden.textContent = Label.textContent;
}
</script>
i thought maybe its because I insert text with textContent,
also , im pretty sure somthing is wrong with the replace.
Many thanks!
HTMLElement hasn't a method indexOf.String owned the method.remeber reset textContent if the textContent changed.
function YellowChair(NumId)
{
if (document.getElementById("CheckBox" + NumId).checked)
{
document.getElementById("ChairImg" + NumId).src = "Images/YellowChair.png";
TypeTheNum(NumId, true);
}
else
{
document.getElementById("ChairImg" + NumId).src = "Images/BlueChair.png";
TypeTheNum(NumId, false);
}
}
function TypeTheNum(NumId,Add)
{
var Label = document.getElementById("SelectedSitsLabel");
var Hidden = document.getElementById("SelectedSitsHidden");
if (Label.innerHTML == "")
{
Label.textContent += NumId;
Hidden.textContent += NumId;
}
else
{
if (Add)
{
Label.textContent += "," + NumId;
}
else
{
// getting stuck here.
if (Label.textContent.indexOf((NumId + ",").toString()) != -1)
{
alert("1");
Label.textContent=Label.textContent.replace((NumId + ",").toString(), "");
}
else
{
alert("ELSE");
Label.textContent=Label.textContent.replace(("," + NumId).toString(), "");
}
}
}
Hidden.textContent = Label.textContent;
}
<button onclick="TypeTheNum('foo')">Remove `foo`</button>
<div id="SelectedSitsLabel">foo,bar,baz</div>
<div id="SelectedSitsHidden"></div>
Label is a DOM element, not a string. So if you need to get characters from the text inside the element, you have to use something like var content = Label.textContent; content.indexOf() and then replace the textContent again after replacing it in the string.
Also as a sidenote, try to look up the differences between innerHTML, textContent and innerText so you can avoid future issues.
The function:
var element = document.getElementById(id);
Returns an Element object, or null but not an string.
Maybe you want to change your code to use textContent property which seems to be the one you are working on like:
if (Label.textContent.indexOf((NumId + ",").toString()) != -1){
alert("1");
Label.textContent.replace((NumId + ",").toString(), "");
}
else{
alert("ELSE");
Label.textContent.replace(("," + NumId).toString(), "");
}
You need to assign the replacement to something:
Label.textContent = Label.textContent.replace(…)

Checking a div for duplicates before appending to the list using jQuery

This should be trivial but I'm having issues...
Basically what I am trying to do is append a new "div" to "selected-courses" when a user clicks on a "course". This should happen if and only if the current course is not already in the "selected-courses" box.
The problem I'm running into is that nothing is appended to the "selected-courses" section when this is executed. I have used alert statements to make sure the code is in fact being run. Is there something wrong with my understanding of the way .on and .each work ? can I use them this way.
Here is a fiddle http://jsfiddle.net/jq9dth4j/
$(document).on("click", "div.course", function() {
var title = $( this ).find("span").text();
var match_found = 0;
//if length 0 nothing in list, no need to check for a match
if ($(".selected-course").length > 0) {
match_found = match(title);
}
if (matched == 0) {
var out = '<div class="selected-course">' + '' + title + ''+'</div>';
$("#selected-box").append(out);
}
});
//checks to see if clicked course is already in list before adding.
function match(str) {
$(".selected-course").each(function() {
var retval = 0;
if(str == this.text()) {
//course already in selected-course section
retval = 1;
return false;
}
});
return retval;
}
There was a couple of little issues in your fiddle.
See fixed fiddle: http://jsfiddle.net/jq9dth4j/1/
function match(str) {
var retval = 0;
$(".selected-course").each(function() {
if(str == $(this).text()) {
retval = 1;
return false;
}
});
return retval;
}
You hadn't wrapped your this in a jquery object. So it threw an exception saying this had no method text().
Second your retval was declared inside the each so it wasn't available to return outside the each, wrong scope.
Lastly the if in the block:
if (matched== 0) {
var out = '';
out += '<div class="selected-course">' + '' + title + ''+'</div>';
$("#selected-box").append(out);
}
was looking at the wrong variable it was looking at matched which didn't exist causing an exception.
Relying on checking what text elements contain is not the best approach to solve this kind of question. It is prone to errors (as you have found out), it can be slow, it gives you long code and it is sensitive to small changes in the HTML. I would recommend using custom data-* attributes instead.
So you would get HTML like this:
<div class="course" data-course="Kite Flying 101">
<a href="#">
<span>Kite Flying 101</span>
</a>
</div>
Then the JS would be simple like this:
$(document).on('click', 'div.course', function() {
// Get the name of the course that was clicked from the attribute.
var title = $(this).attr('data-course');
// Create a selector that selects everything with class selected-course and the right data-course attribute.
var selector = '.selected-course[data-course="' + title + '"]';
if($(selector).length == 0) {
// If the selector didn't return anything, append the div.
// Do note that we need to add the data-course attribute here.
var out = '<div class="selected-course" data-course="' + title + '">' + title + '</div>';
$('#selected-box').append(out);
}
});
Beware of case sensitivity in course names, though!
Here is a working fiddle.
Try this code, read comment for where the changes are :
$(document).on("click", "div.course", function () {
var title = $(this).find("span").text().trim(); // use trim to remove first and end whitespace
var match_found = 0;
if ($(".selected-course").length > 0) {
match_found = match(title);
}
if (match_found == 0) { // should change into match_found
var out = '';
out += '<div class="selected-course">' + '' + title + '' + '</div>';
$("#selected-box").append(out);
}
});
function match(str) {
var retval = 0; // this variable should place in here
$(".selected-course").each(function () {
if (str == $(this).find('a').text().trim()) { // find a tag to catch values, and use $(this) instead of this
retval = 1;
return false;
}
});
return retval; // now can return variable, before will return undefined
}
Updated DEMO
Your Issues are :
1.this.text() is not valid. you have to use $(this).text().
2.you defined var retval = 0; inside each statement and trying to return it outside each statement. so move this line out of the each statement.
3.matched is not defined . it should be match_found in line if (matched == 0) {.
4. use trim() to get and set text, because text may contain leading and trailing spaces.
Your updated JS is
$(document).on("click", "div.course", function () {
var title = $(this).find("span").text();
var match_found = 0;
if ($(".selected-course").length > 0) {
match_found = match(title);
}
if (match_found == 0) {
var out = '<div class="selected-course">' + '' + title + '' + '</div>';
$("#selected-box").append(out);
}
});
function match(str) {
var retval = 0;
$(".selected-course").each(function () {
if (str.trim() == $(this).text().trim()) {
retval = 1;
return false;
}
});
return retval;
}
Updated you Fiddle

Categories