Hangman Game - Repeated string issue - javascript

I was working on my Hangman game, and I have a frustrating issue where once I click the start button to start the game, dashes print to the div not only once, but many times after(once the word to guess has been inputted). I am trying to have the dashes print only once to the div. For example, for the word dog, I want --- to print, and no more dashes after start is pressed. Could you point me in the right direction? Here is the jsfiddle: https://jsfiddle.net/jfn46wjm/
Here is the javascript code for where it appends to the page:
//loop for underscores
//creates under scores for each letter;
for (i = 0; i < input.length; i++) {
placeholder += "-";
}
//append dashes to the page
var grab = document.getElementById("test");
var secret = document.createElement("p");
secret.id = "guessp";
var textn = document.createTextNode(placeholder);
secret.appendChild(textn);
grab.appendChild(secret);

check this Latest jsFiddle
i added a flag printed and checking if it's true before printing any more dashes.
this is the updated link. please check and see if it's working fine.

This part:
var grab = document.getElementById("test");
var secret = document.createElement("p");
secret.id = "guessp";
var textn = document.createTextNode(placeholder);
secret.appendChild(textn);
grab.appendChild(secret);
means that you insert your placeholder ("---") into <div id="test"/>.
In your checkInput method you're calling:
var spguess = document.getElementById("guessp");
And since in your HTML code you have:
<p id="guessp"></p>
<div id="test">
</div>
Then your checkInput method refers to the first <p/> element, while at start you insert new <p id="guessp"/> to your <div id="test">. And then you get this error.

Related

new line for title JavaScript

I'm trying to put every new word for title on the new line using js. I tried different ways, but they don't work.
dictionary.title += word.value; - here I add attribute title for my dictionary class with word.value value. It comes together like: "HelloI'mJohn" instead of
"Hello
I'm
John". How can I do that on the new line using JavaScript code?
Use
\n
or
br tag
for new line.
dictionary.title += word.value + "\n";
Like in the above answers as said you can use <br> and \n for the new line but there are many alternative ways you can achieve this for your understand I have written a code where I used a tag which is also called a block element where it takes given width and height and add a new line at the end automatically. There are many block-level elements you can also use for new lines.
let value = document.querySelector(".newInput");
let btn = document.querySelector("button");
let div = document.querySelector(".dictionary");
function storeValues(){
let dictionary = "";
if(value.value){
dictionary += `<p>${value.value}</p>`
}
div.innerHTML += dictionary
}
btn.addEventListener("click", storeValues);
Enter Word: <input type='text' class='newInput'/>
<button type='submit' class='newInput'>Submit</button>
<div class='dictionary'>
<!-- Dicitonary will appear here-->
</div>

Removing span tags issue if text has encoded characters

I'm looking to remove span tags that wrap blocks of text in an in-browser editor but am having trouble if the text contains any sort of special characters like newline '\n' or encoded characters like , • , etc.
Here's my code that works on sentences without encoded characters
function fnIgnoreThisErr(evtTargID){
// use the passed parameter
var errIdx = evtTargID.substr(evtTargID.indexOf('err-') + 4);
// buld span tag for finding
var errSpan = "span.err-" + evtTargID;
// declare the editor
var editor = CKEDITOR.instances.editor1;
// get text from the editor
var edata = editor.getData();
// find the specific span in the text
var spanData = $( edata ).find(errSpan);
// get outerHTML and innerText to use for replacement
var myCurrText = spanData[0].outerHTML;
var myNewText = spanData[0].innerHTML;
// standard js replace works if no special chars
var replace_text = edata.replace(myCurrText, myNewText); //
// sets the data back in CKEditor
editor.setData(replace_text);
}
Here's an example of the text with the span tag
myCurrText:
<span class=\"vts-warn vts-ParseFailure err-2\">Approval of ICA<br />\n GAMA requested further clarification of proposed §§25.1739 (now §25.1729) and 25.1805(b) (now §26.11(b)) requirements that ICA prepared in accordance with paragraph H.</span>
And with the span tag removed.
Approval of ICA<br />\n GAMA requested further clarification of proposed §§25.1739 (now §25.1729) and 25.1805(b) (now §26.11(b)) requirements that ICA prepared in accordance with paragraph H.
It works great on plain sentences without any encoded characters. I can switch to jQuery but couldn't get replaceWith to work either.
What am I missing here?
I figured it out. There appears to be a discrepancy between html entities and the way they are being rendered/interpreted by the browser and my JS.
i.e. The outerHTML of the span is not a character-for-character match of the text in edata.
So I just get the indexOf value for the start of the span and the length of the span node. However, due to the discrepancy mentioned, this length may include additional characters. So, next, I find the exact position of the '' tag. From there, I build a string variable that exactly matches the text that needs to be replaced.
Here's my final code. (I kept it long-form for clarity)
function fnIgnoreThisErr(evtTargID){
// use the passed parameter
var errIdx = evtTargID.substr(evtTargID.indexOf('err-') + 4);
// buld span tag for finding
var errSpan = "span.err-" + evtTargID;
// declare the editor
var editor = CKEDITOR.instances.editor1;
// get text from the editor
var edata = editor.getData();
// find the specific span in the text
var spanData = $( edata ).find(errSpan);
// extract the span class name
var spanTag = '<span class="'+spanData[0].className+'">'
// find indexOf value for the span opening tag
var spanPos = edata.indexOf(spanTag);
// get the initial length of the span.
var spanLength = spanData[0].outerHTML.length;
// get the actual text from that span length.
var spanString = edata.substring(spanPos,spanPos+spanLength);
// find the acutal position of the span closing tag
var spanClose = spanString.indexOf('</span>');
var spanTagClosePos = spanClose+7;
// extract the true text comprising the span tag
var spanStringMod = edata.substring(spanPos,spanPos+spanTagClosePos);
var spanInnerHtm = spanData[0].innerHTML;
log("errSpan: "+ errSpan);
log("errSpanClass: "+ errSpanClass);
log("spanData: "+ JSON.stringify(spanData));
log("spanPos: "+ spanPos);
log("spanTagClosePos: "+ spanTagClosePos);
log("spanStringMod: "+ spanStringMod);
log("spanInnerHtm: "+ spanInnerHtm);
var newEdata = edata.replace(spanStringMod, spanInnerHtm);
log(" newEdata: "+ newEdata);
// update the editor
editor.setData(newEdata);
}
I hope this helps someone, somewhere, at some time!
Cheers!

javascript arrays and looping

I'm jessi and I'm a web development student. I'm trying to write a program with arrays and I'm stuck. I have an array of phrases and when a user enters a number between 1 and 10 it is supposed to show that many phrases on the screen but I'm stuck. I don't know how to display multiple results on the screen. I'd really appreciate any help. Thanks.
<!DOCTYPE html>
<html>
<head>
<title>Get A Response</title>
</head>
<body>
<form>
<h1>Select how many phrases you want displayed.</h1>
<input type="number" class="userInput"></input>
<button type="submit" value="submit" onclick="showme()"></button>
</form>
<div class="myphrases">
</div>
<script src="js/main.js"></script>
</body>
</html>
////////////////// Javascript
function showme() {
var number = document.querySelector('.userInput').value;
var display = "";
var phrases = [
"Hello there",
"What's up Doc",
"Because I said so",
"Say it again",
"It's a celebration",
"Enjoy yourselves",
"Welcome",
"Where did you go", "Why you crying", "Stop playing"];
var random = Math.floor(Math.random() * phrases.length);
for(var i = 0; i < phrases.length; i++) {
}
}
First, you should set up an HTML element that will serve as your output area. An empty div element is a good choice. You've already done that with: <div class="myphrases"></div>.
Next, the HTML input element does not get a closing tag (</input>) and instead of using a submit button, just use a regular button (since you are not actually submitting data anywhere).
Also, don't use inline HTML event handling attributes (onclick, onmouseover, etc.) as they:
Create spaghetti code that leads to duplication and makes the code harder to read.
Causes global anonymous wrapper functions to be created around your attribute's value and change the this binding in your callback functions.
Don't follow the W3C Event standard of using .addEventListener().
Next, don't have your loop go over every phrase (phrases.length). Only have it go for the amount of times the user has entered.
Finally, you can update the div output area by adjusting its innerHTML to be a string that you build up from your loop:
// Get reference to the text box, the button and the output area
var number = document.querySelector('.userInput');
var btn = document.querySelector("button");
var output = document.querySelector(".myphrases");
// Set up the event handling function for the button
btn.addEventListener("click", showme);
function showme() {
var display = "";
var phrases = [
"Hello there",
"What's up Doc",
"Because I said so",
"Say it again",
"It's a celebration",
"Enjoy yourselves",
"Welcome",
"Where did you go", "Why you crying", "Stop playing"];
// String to hold loop results
var result = "";
// Set up the upper limit for the loop.
// If the entered value is greater than the length of the array, use the length
// of the array. If not, use the value entered by the user
var count = number.value > phrases.length ? phrases.length : number.value;
for(var i = 0; i < count; i++) {
var random = Math.floor(Math.random() * phrases.length);
result += phrases[random] + "<br>";
}
// Inject the string into the output area
output.innerHTML = result;
}
<form>
<h1>Select how many phrases you want displayed.</h1>
<input type="number" class="userInput">
<button type="button">Submit</button>
</form>
<div class="myphrases"></div>

Display Form Input as Stylized String - Javascript

I am trying to take input from a number field and display it somewhere else on the page.
Here is my HTML
<input id="dollar" type="text" name="mytextfield2" onkeyup="updateDollarDisplay();">
<div id="dollarValue"></div>
and my javascript
function convertDigitsToArray(number){
var s = parseInt(number).toString(10).split("").map(Number);
return s;
}
function updateDollarDisplay() {
var amount = $('#dollar').value;
var a = convertDigitsToArray(amount);
console.log(a[0]);
$('#dollarValue').text(a[0]);
}
Running the exact code in a javascript interpreter works fine, it gives me each digit as an element in the array. When I try to do the same through the HTML page it gives me NaN each time. Any ideas?
Fiddle here: http://jsfiddle.net/7mzo8eb5/2/ I'd like it to show to input in the grayed div on each input.
The problem is with var amount = $('#dollar').value;
value is not an attribute, but val is a function. Should be: var amount = $('#dollar').val();

Match a String in a Webpage along with HTML tags

With below code, I am trying to match a text in a web page to get rid of html tags in a page.
var body = $(body);
var str = "Search me in a Web page";
body.find('*').filter(function()
{
$(this).text().indexOf(str) > -1;
}).addClass('FoundIn');
$('.FoundIn').text() = $('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>");
But it does not seems to work.. Please have a look at this and let me know where the problem is...
here is the fiddle
I have tried the below code instead..
function searchText()
{
var rep = body.text();
alert(rep);
var temp = "<font style='color:blue; background-color:yellow;'>";
temp = temp + str;
temp = temp + "</font>";
var rep1 = rep.replace(str,temp);
body.html(rep1);
}
But that is totally removing html tags from body...
change last line of your code to below one...you are using assignment operator which works with variables not with jquery object ..So you need to pass the replaced html to text method.
$('.FoundIn').text($('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>"))
try this.
$('*:contains("Search me in a Web page")').text("<span class='redT'>Search me in a Web page</span>");

Categories

Resources