Reading textbox input and putting in one of two boxes javascript - javascript

I am trying to allow the user to enter 1 letter in a text box, and then the letters gets put into 1 of 2 boxes. This is for a hangman game, so it is going to divide the letters based on whether or not it is in the word. Here's my code. Hopefully someone can help me. I'm new to javascript! I've done a ton of googling, but to little avail.
var words = ['dog', 'computer', 'cat', 'monkey', 'human'];
var wordForGuess = chooseWord();
var wordLength = wordForGuess.length;
function chooseWord () {
return words[Math.floor(Math.random() * words.length)];
}
function writeWord()
{
var textarea = document.getElementById('textBox').value;
for (var x = 0; x<wordLength; x++)
{
if (textarea === wordForGuess.indexOf(x))
{
document.getElementById('correctLetters').value = textarea;
}
else
{
document.getElementById('incorrectLetters').value = textarea;
}
}
}
As well as the HTML for my textbox
<div id = 'letterInput'>
</div>
<input type = 'text' id = 'textBox' onkeyUp="writeWord()"/>
<div id = 'correctLetters'>
</div>
<div id = 'incorrectLetters'>
</div>

I think you have a few mistakes, including iterating over your characters in your chosen word and using the index of that iteration instead of just checking the value from the input box. I also think you should reset the value on each keyup. I also moved your onkeyup event out of the HTML into JavaScript, I think maybe in your case the JavaScript hadn't loaded yet but it's hard to tell from your example.
<div id = 'letterInput'>
</div>
<input type = 'text' id = 'textBox' />
<br/>
Correct:
<div id = 'correctLetters'>
</div>
<br/>
Incorrect
<div id = 'incorrectLetters'>
</div>
Here's the JavaScript with some fixes:
var words = ['dog', 'computer', 'cat', 'monkey', 'human'];
var wordForGuess = chooseWord();
var wordLength = wordForGuess.length;
function chooseWord () {
return words[Math.floor(Math.random() * words.length)];
}
function writeWord() {
var input, textarea;
input = document.getElementById('textBox')
textarea = input.value;
input.value = "";
console.log("writing word", textarea);
if (wordForGuess.indexOf(textarea) !== -1) {
document.getElementById('correctLetters').innerText += textarea;
} else {
document.getElementById('incorrectLetters').innerText += textarea;
}
}
document.getElementById("textBox").onkeyup = writeWord;
Here's a jsfiddle with this code.

Related

How do I use a loop to pick random characters from an array

So I am working on a password generator and I have an array of possible characters, populated from user choices. I am trying to get random characters from the array the length of the users chosen password length, but it is only returning one character. Can anyone tell me what I'm doing wrong please?
// function to prompt user for desired password length
function getLength() {
let passwordLength = prompt("Pick a length between 10 and 64 characters");
let passwordLengthValue = passwordLength.valueOf();
if (passwordLength >= 10 && passwordLength <= 64) {
return passwordLengthValue;
} else if (passwordLength < 10 || passwordLength > 64) {
alert("You must pick a value between 10 and 64");
}
if (confirm("do you want to try again")){
return getLength();
}
}
var passwordBase = [];
// Function to prompt user for password options
function getCharacterTypes() {
if (confirm("Do you want lowercase characters?")) {
passwordBase = passwordBase.concat(lowerCasedCharacters)
};
if (confirm("Do you want uppercase characters?")) {
passwordBase = passwordBase.concat(upperCasedCharacters)
};
if (confirm("Do you want numbers?")) {
passwordBase = passwordBase.concat(numericCharacters)
};
if (confirm("Do you want special characters")) {
passwordBase = passwordBase.concat(specialCharacters)
};
if (passwordBase.length > 0) {
return passwordBase;
} else {
(confirm("do you want to try again"))
return getCharacterTypes()
};
}
var characterTotal = getLength();
var randomCharacter = []
// Function for getting a random element from an array
function getRandom(passwordBase) {
for (i = 0; i < characterTotal.length; i++) {
randomCharacter = passwordBase[Math.floor(Math.random() * passwordBase.length)];
return randomCharacter;
}
};
I have tried passing different arrays into the getRandom() function, and I tried it without the for loop but get the same single character result.
The way your function is written, you are replacing the variable randomCharacter in each iteration of the loop. What you need to do is to add the random character that you're trying to get from the passworBase to the array that you have defined.
// Function for getting a random element from an array
function getRandom(passwordBase) {
for (i = 0; i < characterTotal.length; i++) {
randomCharacter.push(passwordBase[Math.floor(Math.random() * passwordBase.length)]);
}
return randomCharacter;
};
Zgjim's answer points out a good note in your code, I have something similar that you might find value in though it's not an exact answer to your code. It's a variation of how to accomplish this, though I incorporated html for selecting size / content of the password generated. Hopefully you find value in it!
const $ = str => [...document.querySelectorAll(str)];
const passEl = $("#pass-len")[0];
const optionEls = $("input.options");
const generate = $("#generate")[0];
const display = $("#display")[0];
const charLookup = {
lowercase: "abcdefghijklmnopqrstuvwxyz",
uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
numbers: "1234567890",
special: "!##$%^&*()"
};
// Function for getting a random element from an array
function generatePassword() {
const len = passEl.value;
const options = optionEls.filter(el => el.checked).map(el => el.value);
const charStr = options.reduce((a,b) => a + charLookup[b], "");
const avaliableChars = [...charStr];
const max = avaliableChars.length;
let password = "";
for (let i = 0; i < len; i++) {
const randomIndex = Math.floor(Math.random() * max);
password += avaliableChars[randomIndex];
}
return password;
}
generate.addEventListener("click", () => {
const pass = generatePassword();
display.innerText = pass;
});
body {
background-color: lavender;
}
label {
user-select: none;
outline: 1px solid black;
}
label:hover {
outline: 1px solid lightgreen;
}
password length: <input id="pass-len" type="range" min="10" max="64" /> <br />
options:
<label>lowercase <input value="lowercase" class="options" type="checkbox"></label>
<label>uppercase <input value="uppercase" class="options" type="checkbox"></label>
<label>numbers <input value="numbers" class="options" type="checkbox"></label>
<label>special characters <input value="special" class="options" type="checkbox"></label> <br />
<button id="generate">generate</button>
<span id="display"></span>
Just as a note, Math.random should not be used as a password generator in production because it is not safe. There are libraries that exist for password generation and are more secure, if that interests you! Good luck 👍

How to compare 2 text input values?

I'm trying to create a simple game where you have to answer the correct answer from a calculation.
I already have the function to generate random calculations, but i don't know how to compare it with the result which the user writted.
I tried to make the if, so when the user press the submit button, then the app will try to determine if that's the correct answer.
var numArray = ["10/2", "5x5", "12-22", "5-6", "20-70"];
var question = document.getElementById("textQuestion");
var answer = document.getElementById("textAnswer");
function rollDice() {
document.form[0].textQuestion.value = numArray[Math.floor(Math.random() * numArray.length)];
}
function equal() {
var dif = document.forms[0].textQuestion.value
if (dif != document.forms[0].textAnswer.value) {
life--;
}
}
<form>
<input type="textview" id="textQuestion">
<br>
<textarea id="textAnswer" form="post" placeholder="Answer"></textarea>
</form>
<input type="button" name="start" onclick="">
document.forms[0].textQuestion.value looking for an element with name=textQuestion, which doesn't exist. Use getElementById instead or add name attribute (needed to work with the input value on server-side).
function equal() {
if (document.getElementById('textQuestion').value != document.getElementById('textAnswer').value) {
life--; // life is undefined
}
}
// don't forget to call `equal` and other functions.
This is probably what you're looking for. I simply alert(true || false ) based on match between the random and the user input. Check the Snippet for functionality and comment accordingly.
var numArray = ["10/2", "5x5", "12-22", "5-6", "20-70"];
var questionElement = document.getElementById("textQuestion");
var answerElement = document.getElementById("textAnswer");
function rollDice() {
var question = numArray[Math.floor(Math.random() * numArray.length)];
questionElement.setAttribute("value", question);
}
//rolldice() so that the user can see the question to answer
rollDice();
function equal()
{
var dif = eval(questionElement.value); //get the random equation and evaluate the answer before comparing
var answer = Number(answerElement.value); //get the answer from unser input
var result = false; //set match to false initially
if(dif === answer){
result = true; //if match confirmed return true
}
//alert the match result
alert(result);
}
document.getElementById("start").addEventListener
(
"click",
function()
{
equal();
}
);
<input type="textview" id="textQuestion" value="">
<br>
<textarea id="textAnswer" form="post" placeholder="Answer"></textarea>
<input type="button" id="start" value="Start">
There's more I would fix and add for what you're trying to achieve.
First of you need a QA mechanism to store both the question and the correct answer. An object literal seems perfect for that case: {q: "", a:""}.
You need to store the current dice number, so you can reuse it when needed (see qa_curr variable)
Than you could check the user trimmed answer equals the QA.a
Example:
let life = 10,
qa_curr = 0;
const EL = sel => document.querySelector(sel),
el_question = EL("#question"),
el_answer = EL("#answer"),
el_check = EL("#check"),
el_lives = EL("#lives"),
qa = [{
q: "Calculate 10 / 2", // Question
a: "5", // Answer
}, {
q: "What's the result of 5 x 5",
a: "25"
}, {
q: "5 - 6",
a: "-1"
}, {
q: "Subtract 20 from 70",
a: "-50"
}];
function rollDice() {
qa_curr = ~~(Math.random() * qa.length);
el_question.textContent = qa[qa_curr].q;
el_lives.textContent = life;
}
function checkAnswer() {
const resp = el_answer.value.trim(),
is_equal = qa[qa_curr].a === el_answer.value;
let msg = "";
if (resp === '') return alert('Enter your answer!');
if (is_equal) {
msg += `CORRECT! ${qa[qa_curr].q} equals ${resp}`;
rollDice();
} else {
msg += `NOT CORRECT! ${qa[qa_curr].q} does not equals ${resp}`;
life--;
}
if (life) {
msg += `\nLives: ${life}`
} else {
msg += `\nGAME OVER. No more lifes left!`
}
// Show result msg
el_answer.value = '';
alert(msg);
}
el_check.addEventListener('click', checkAnswer);
// Start game
rollDice();
<span id="question"></span><br>
<input id="answer" placeholder="Your answer">
<input id="check" type="button" value="Check"> (Lives:<span id="lives"></span>)
The above still misses a logic to not repeat questions, at least not insequence :) but hopefully this will give you a good start.

How to remove innerHTML value to be shown initially

I am trying to create a multiplication table in JavaScript. The user is prompted to provide the Table number (1 to 10) after which all the question marks ('?') are replaced with that number. The user then needs to enter the answers in all the provided text fields. Finally, the user will have the option to check the answer (i.e. whether it is right or wrong).
When I run my code. After entering the user data to prompt it shows Incorrect infront of each textfield and the user entered value just before the Check answers button. How can I remove them to be shown initially.
Output:
My code:
function result() {
var value = document.getElementById("a1").value;
var checkMessageSpan1 = document.getElementById("checkMessage1");
var checkMessageSpan2 = document.getElementById("checkMessage2");
var r = x * 1;
if (value == x) {
checkMessageSpan1.innerHTML = "<span style=\"color:green\">"+"Correct!";
}else{
checkMessageSpan1.innerHTML = "<span style=\"color:red\">"+"Incorrect!";
}
var value = document.getElementById("a2").value;
var r = x * 2;
if (value == r) {
checkMessageSpan2.innerHTML = "<span style=\"color:green\">"+"Correct!";
}else{
checkMessageSpan2.innerHTML = "<span style=\"color:red\">"+"Incorrect!";
}
</script>
<button onClick="alert_field()"> Generate Question</button><br><br>
<p id="s1">
? x 1 = <input type="text" id="a1"><span id="checkMessage1"></span><br>
? x 2 = <input type="text" id="a2"><span id="checkMessage2"></span><br>
</p><br><br>
<p id="a"></p>
Check answers
For replacing all special characters, you may leverage regular expressions in js
var res=str.replace(/[^a-zA-Z0-9]/g,x); instead of
var res = str.replace("?",x);
More on Regular expressions in JS https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Try to add this code:
var value = document.getElementById("a1").value;
if (checkMessageSpan1.style.display === "none") {
checkMessageSpan1.style.display = "inline-block";
} else {
checkMessageSpan1.style.display = "none";
}
var value = document.getElementById("a2").value;
if (checkMessageSpan2.style.display === "none") {
checkMessageSpan2.style.display = "inline-block";
} else {
checkMessageSpan2.style.display = "none";
}

Getting comma separated values into input field

I am struggling already for some time to create script that deletes and adds values to field. The point is that when I click on div - there will be images inside, it will copy part of its class to field, or remove if it's already copied there. All the values in field input_8_3 need to be comma separated without spaces except the last one and in case there is only one value there shouldn't be any comma. The same with field input_8_4, but there I need only erased values.
In addition I need divs to change class on click, one click to add class, another to remove it, but this is how far could I get with my issue.
I need this for deleting images in custom field in Wordpresses frontend. input_8_3 goes to meta and input_8_4 to array in function to delete chosen images.
Thanks in advance!
(function($){
$('.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','')+',';
var oldtext = $('#input_8_3').val();
$('#input_8_3').val(text+oldtext);
});
})(jQuery);
(function($){
$('div.thumbn').click(function() {
$(this).removeClass('chosen-img');
});
})(jQuery);
(function($){
$('.thumbn').click(function() {
$(this).addClass('chosen-img');
});
})(jQuery);
.thumbn {
width: 85px;
height: 85px;
background: #7ef369;
float: left;
margin: 10px;
}
.chosen-img.thumbn{background:#727272}
input{width:100%}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="input_8_3" readonly="" value="3014,3015,3016,3017,3018" class="form-control data_lable">
<input type="text" id="input_8_4" readonly="" value="" class="form-control data_lable">
<div class="user-profile-avatar user_seting st_edit">
<div>
<div class="thumbn" id="img-act-3014"></div>
<div class="thumbn" id="img-act-3015"></div>
<div class="thumbn" id="img-act-3016"></div>
<div class="thumbn" id="img-act-3017"></div>
<div class="thumbn" id="img-act-3018"></div>
</div>
</div>
EDIT: I changed value of input_8_3. All the numbers in img-act-**** and values in input_8_3 are the same on load.
I've made a JS of it working.
https://jsfiddle.net/jatwm8sL/6/
I've added these:
var array = [3008,3009,3010,3011,3012];
$("#input_8_3").val(array.join());
and changed your click functions to this
var array = [3008,3009,3010,3011,3012];
var array1 = [];
$("#input_8_3").val(array.join());
(function($){
$('div.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','');
var oldtext = $('#input_8_3').val();
if ($(this).hasClass('chosen-img'))
{
$('#input_8_3').val(text+oldtext);
var index = array.indexOf(text);
if (index !== -1)
{
array.splice(index, 1);
}
array1.push(text);
$(this).removeClass('chosen-img');
}
else
{
array.push(text);
var index = array1.indexOf(text);
if (index !== -1)
{
array1.splice(index, 1);
}
$(this).addClass('chosen-img');
}
$("#input_8_3").val(array.join());
$("#input_8_4").val(array1.join());
console.log(array1);
});
})(jQuery);
Basically, you need to check if it has a class and then remove if it has and add it if it doesn't.
Also, it's better to use a javascript array than to play around with html values as you change javascript arrays while HTML should really just display them.
If anything is unclear, let me know and I'll try to explain myself better
var transformNumbers = (function () {
var numerals = {
persian: ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"],
arabic: ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"]
};
function fromEnglish(str, lang) {
var i, len = str.length, result = "";
for (i = 0; i < len; i++)
result += numerals[lang][str[i]];
return result;
}
return {
toNormal: function (str) {
var num, i, len = str.length, result = "";
for (i = 0; i < len; i++) {
num = numerals["persian"].indexOf(str[i]);
num = num != -1 ? num : numerals["arabic"].indexOf(str[i]);
if (num == -1) num = str[i];
result += num;
}
return result;
},
toPersian: function (str, lang) {
return fromEnglish(str, "persian");
},
toArabic: function (str) {
return fromEnglish(str, "arabic");
}
}
})();
document.getElementById('ApproximateValue').addEventListener('input', event =>
event.target.value = TolocalInt(event.target.value)
);
function TolocalInt(value)
{
if ((value.replace(/,/g, '')).length >= 9) {
value = value.replace(/,/g, '').substring(0, 9);
}
var hasZero = false;
var value = transformNumbers.toNormal(value);
var result = (parseInt(value.replace(/[^\d]+/gi, '')) || 0);
if (hasZero) {
result = '0' + (result.toString());
}
return result.toLocaleString('en-US');
}
<input id="ApproximateValue" name="ApproximateValue" type="text" maxlength="12" />

Create an array of external html pages and shuffle it into several divs

I'm currently working on a site that consists in a grid of divs (4x4) into which a set of texts have to be shuffled at each reload. This basically looks like this at the moment.
My index.htm reads :
<div class="container">
<div class="colonne">
<div class="case">
<span class="boxwatermark">1</span>
<span class="case1">
</span>
</div>
<div class="case">
<div class="boxwatermark">5</div>
<span class="case5">
</span>
</div>
<div class="case">
<div class="boxwatermark">9</div>
<span class="case9">
</span>
</div>
...
and so on up to 15 (16 remains empty).
The set of texts that I need to be distributed into the boxes (boxes = divs with classnames "case+number") are each in a separate html file (named "case1.html", "case2.html" etc.). I would like these html files to constitute the array, and this array to be shuffled "randomly" into each box.
I tried several things for the past two days, but the solution to this problem seems presently to exceed my (little) competences... I've been impressed by some of the attention given to such questions on this forum and decided to request your help. Thanks !
Try using Array.prototype.slice(), Array.prototype.splice() , .eq() , .each() , .load()
$(function() {
var c = "case";
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var copy = arr.slice(0);
$("." + c).each(function() {
var curr = copy.splice(Math.floor(Math.random() * copy.length), 1)[0];
$(this).load(c + curr + ".html")
})
})
plnkr http://plnkr.co/edit/rAhq6fkbUqM3BfnahAVy?p=preview
try this https://fiddle.jshell.net/
var shuffle = function (htmls) {
for (var j, x, i = htmls.length; i; j = parseInt(Math.random() * i), x = htmls[--i], htmls[i] = htmls[j], htmls[j] = x);
return htmls;
};
var display = function (shuffledArray) {
var index = 0;
for (var spot in shuffledArray) {
index++;
var cssClass = '.case' + index;
var div = document.querySelector(cssClass);
div.innerHTML = shuffledArray[spot];
}
}
if (!sessionStorage.getItem('htmlFiles')) {
var htmls = [];
htmls[0] = 'this a text for example';
htmls[1] = 'Another text for example';
htmls[2] = 'Yet anohter text for example';
htmls[3] = 'The texts keep up comming';
htmls[4] = 'More example texts here';
htmls[5] = 'Even more texts';
htmls[6] = 'The last example';
sessionStorage.setItem('htmlFiles', htmls);
}
var htmls = sessionStorage.getItem('htmlFiles').split(',');
var shuffledArray = shuffle(htmls);
display(shuffledArray);

Categories