I have a set of buttons set up with id, keys, values etc,
And an array with different values.
I want the user to be able to click on any button and this select at random from the array, this will when remove an image from the screen matching the value randomly picked from the array. It’s frustrating as I have been trying for ages! HELP!
function getrandom(){
var random = amounts[Math.floor(Math.random() * amounts.length)];
document.getElementById("task").innerHTML= "Your selected button revealed " + random;
for( var i = 0; i < amounts.length; i++){
if ( amounts[i] === random) {
arr.splice(i, 1);
}
}
}
Your code doesn't need a for-loop. Try this instead:
function getrandom() {
var randomIndex = Math.floor(Math.random() * amounts.length);
var random = amounts[randomIndex];
document.getElementById("task").innerHTML= "Your selected button revealed " + random;
amounts.splice(randomIndex, 1);
}
The root of your problem might have had something to do with the fact that you weren't "break;"ing out of the loop after you found the value, and so the loop kept going, checking all the other values. But because you had already removed an item from the array, it would potentially go out-of-bounds.
If this still doesn't work, you might be getting a null pointer error on the line:
document.getElementById("task").innerHTML= "Your selected button revealed " + random;
Check to make sure the "task" element actually exists in the HTML.
Related
For context, just starting with JS, and wanted to do something simple, create a Higher/Lower guessing game. I have it fully working, though I wanted to add some more color to it, so my idea is to create a list of previously guessed numbers and whether that number is higher or lower than the target number (the number that they have to guess). though I currently have it set up where
const guesses = document.querySelector(".guesses");
and
guesses.textContent += userGuess + ' ';
so it just creates this extremely long, sentence-like line of previously guessed numbers that is in all white. Is there any way for me to change it so that each individual guess can somehow be listed and can be either red or green depending on if the target number is higher or lower?
For the if, else, and else if statements, I just have it so that it shows a certain text stating if the guess is too high or too low, and if it's exact, then it gives the option to restart the game
Edit, more parts of the code:
js:
let userGuess = guessField.valueAsNumber
const guessField = document.getElementById('guessField');
guessField is just an input tag in HTML
then in js, I have it generate some number, save that as randomNumber with let randomNumber = Math.floor(Math.random() * 100 + 1)
then if userGuess === randomNumber then show a p tag saying that it's right, and give it a green background or else say it's wrong (that p tag). Then I have it look if the userGuess number is lower or higher than the target number (aka the randomNumber) if it's too high, show a paragraph saying it's too high, and if it's too low, show a paragraph saying it's too low.
Add guesses in a list instead of just as text in a div. Add backgroundColor style to the result p tag to show whether guess is higher or lower or correct.
let randomNumber = Math.floor(Math.random() * 10 + 1)
const guesses = document.querySelector("#guesses");
const result = document.querySelector("#result");
function checkNum() {
let guessField = document.getElementById('guessField');
let userGuess = parseInt(guessField.valueAsNumber, 10);
var node = document.createElement("li");
var textnode = document.createTextNode(userGuess);
node.appendChild(textnode);
guesses.appendChild(node);
guessField.value = "";
result.style.backgroundColor = "tomato";
if (userGuess === randomNumber) {
result.style.backgroundColor = "aquamarine";
result.innerHTML = "You are right";
} else if (userGuess < randomNumber) {
result.innerHTML = "Guess is lower";
} else {
result.innerHTML = "Guess is higher";
}
}
p {
font-weight: bold;
}
<ul id="guesses">
</ul>
<input type="number" id="guessField" />
<button onclick="checkNum()">check</button>
<p id="result"></p>
We have very minimal info here on what you would like to accomplish and the code you are using however I think we'll be able to help you out here :)
there are a few approaches you can take here, I'm not sure if you're using any databases for your use case but since you're starting off I'm going to assume you simply want to store the values submitted via the input field in an array and later iterate through the array in an effort to pull values from it and perform operations with each iteration.
first you would need to declare an array:
const guessedNumbers = [];
next to store the values from user input you would need to to create a submit event listener on your form that will invoke a function to store the value user submits in the guessedNumbers array. In order to store the values in the guessedNumbers array you can use the .push method:
form = document.querySelector('your-form-selector');
form.addEventListener('submit', (e) => {
const userInputValue = document.querySelector('your-input-field-selector').value;
guessedNumbers.push(userInputValue);
});
Now if you need to access the values stored in the guessedNumbers array, there are multiple built in methods that allow you to accomplish this. Have a look at this MDN link that will shed some light on these array methods. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
for example you may want to iterate through each value in the array and console.log each iteration's value:
guessedNumbers.forEach((number) => console.log(number))
Happy coding!
Update: The difference is I'm not trying to make one list I'm trying to make a button that can be clicked and generate a random name
Goal: Click a button and randomly generate a name from an array. I'm trying to be able to click the button and show one name randomly at a time with no repeating names. So far I've been able to randomly select a name but the names still repeat. How could I change my code to avoid any repeating names?
$( ".next").click(function() {
$(".intro").hide()
var people = ["Andrew", "Adam", "Seth", "Mattos", "Eric"];
for(i=0;i<1;i++){
var randomPosition = Math.floor(Math.random() * people.length);
var selected = people.splice(randomPosition,1);
console.log(selected)
$('#person').text(selected)
if ($('#person').text() === "Mattos"){
$("#selectedPerson").text("Mattos")
}
if ($('#person').text() === "Andrew"){
$("#selectedPerson").text("Andrew")
}
if ($('#person').text() === "Eric"){
$("#selectedPerson").text("Eric")
}
if ($('#person').text() === "Seth"){
$("#selectedPerson").text("Seth")
}
if ($('#person').text() === "Adam"){
$("#selectedPerson").text("Adam")
}
}
});
The problem is that you're creating the array every time you enter the function. So splicing the name out of the array has no effect, because you'll refill it the next time. You need to move the array initialization out of the function.
Other issues: splice() returns an array, not a single element, even if you're only splicing out 1 element from the array. You don't need a for() loop if you're only looping 1 time. All the if statements were unneeded, since you're just assigning the same strings in all cases.
And you should check for the case where you've run out of names.
var people = ["Andrew", "Adam", "Seth", "Mattos", "Eric"];
$( ".next").click(function() {
$(".intro").hide();
if (people.length == 0) { // No names left to show
return;
}
var randomPosition = Math.floor(Math.random() * people.length);
var selected = people[randomPosition];
people.splice(randomPosition,1);
console.log(selected)
$('#person,#selectedPerson').text(selected);
});
I have created a function, updatePrice, which I have tied to the "click" event on the checkbox and radio buttons in my HTML form. Each checkbox and radio basically represents an item, with it's price as the value property of these <input> elements. When I check or uncheck any box, the function fires, loops through all elements in the form, and updates the total price of all the checked items into a div element I have below my form, with the id tag "priceOutput".
The following code works perfectly, printing out: The price of this item is $(price of item).
function updatePrice() {
var price = 0
for (i=0;i<=form.length;i++) {
var element = form[i]
if(element.checked) {
price+=parseInt(element.value)
}
document.getElementById("priceOutput").innerHTML = "The price of this item is $" + price + "."
}
}
But, if I switch the the last line around, the line is not printed at all:
function updatePrice() {
var price = 0
for (i=0;i<=form.length;i++) {
var element = form[i]
if(element.checked) {
price+=parseInt(element.value)
}
}
document.getElementById("priceOutput").innerHTML = "The price of this item is $" + price + "."
}
Why must I write the line in the {} of the for in order to work. Doesn't the price variable's scope extend over the entire updatePrice function?
I'm still rather new to programming, so do forgive me if this is an elementary question.
It seems to me that it isn't printing because you are causing an error. Since array indexing starts at 0 your for loop should not use <= but rather < :
for (i=0;i<form.length;i++) {
...
}
The reason why nothing gets printed then is because on the last loop the function errors and you setting the inner HTML never gets executed.
Seems like there is an error with your code, how about adding var to your for loop and removing the = from i<=form.length
for (var i = 0; i < form.length; i++)
I'm trying to delete an item from an array and add it to another array. The array states consists of a list of 50 states. User needs to enter the name of a state and the state must get deleted from states array and get added to the array correctState. Here is my code
function searchString()
{
var total = 50;
var string = document.getElementById("txtState").value;
var element = document.getElementById("status");
for (i=0; i < states.length; i++)
{
if(states[i].toUpperCase() == string.toUpperCase())
{
count = count + 1;
//element.innerHTML = "CORRECT!!!"
addElem = states.splice(i,1);
correctState.push(addElem);
/*for (j=0; j < correctState.length; j++)
{
if(correctState[j].toUpperCase() == string.toUpperCase())
{
element.innerHTML = "Already Submitted. Try another State";
}
}*/
}
document.getElementById("score").innerHTML = count +"/"+ total;
document.write(states);
document.write(correctState);
}
}
Enter State : <input type="text" name="txtState" id="txtState"><span id="timer"></span><br /><span id="status"></span>
<button type="button" name="btnPlay" id="btnPlay" accesskey="s" onClick="searchString()"><u>S</u>ubmit</button>
I'm not able to achieve what I need. I'm new to javascript and need help.
Re these lines:
addElem = states.splice(i,1);
correctState.push(addElem);
splice doesn't return the element that you remove, it returns an array of those elements. So your code is pushing array instances onto correctState. I'd do this:
correctState.push(states[i]); // First push the matching state onto `correctStates`
states.splice(i,1); // ...then remove it
Alternately, you could do it in the order you showed, you just have to get the removed element out of the array you get back
addElem = states.splice(i,1);
correctState.push(addElem[0]);
// Here -----------------^^^
but again, I'd do it by pushing first, then removing.
Separately, I'd use the debugger built into your browser to single-step through that code and watch it run. I suspect you'll find that you want to move some things around, and you almost certainly want to stop looping once you've found that string matches something in the array.
My guess is that it's the fact that you're modifying your states array while you are still enumerating.
So say you're states array is [AR, LA, CT] and the user entered LA. So your for loop goes like this
i = 0 (length is 3 so i < 3)
string not found
i = 1 (length is 3 so i < 3)
string found, remove it from states
i = 2 (length is 2 so i < 2 fails and there's no final loop)
What you probably want is just something like this
function moveAllInstancesBetweenArrays(val, source, destination) {
var indexOfVal = source.map(function(s) { return s.toUpperCase() })
.indexOf(val.toUpperCase());
if(indexOfVal == -1)
return;
source.splice(indexOfVal, 1);
destination.push(val);
moveAllInstancesBetweenArrays(val, source, destination); //continue until all matching are moved
}
moveAllInstancesBetweenArrays(yourSearchVal, states, correctStates);
I have a form with 10 Select Lists all have the same items. The items are populated from a PHP/MySQL array. The user needs to select one item per select list. I need to prevent the user from selecting the same item twice before submitting the form.
function checkDropdowns(){
var iDropdowns = 10;
var sValue;
var aValues = new Array();
var iKey = 0;
for(var i = 1; i <= iDropdowns; ++i){
sValue = document.getElementById('test' + i).value;
if ( !inArray(sValue, aValues) ){
aValues[iKey++] = sValue;
}else{
alert('Duplicate!');
return false;
}
}
return true;
}
Use javascript to add an event listener on the value change of the selects. That function would then loop through the selects taking the values into memory after having compared it to the values it had already. If the loop finds that the current select has an option that is already selected, put it back to default value and display a little message...
Or, still on a change event, take the value of the just selected item and remove all the items of this value in the 10 selects. So at the end the user will only have 1 choice, since he only sees the options he can choose. But be careful, if the user changes his mind on one select, make sure you add back the option you removed in the first place.
Option 2 is to be prefered as a user point of view, you will cause less frustration.
EDIT:
The code you are providing already does quite a lot... All you need now is something to revert the change if it is invalid:
var defaultValues = [];
function onLoadSelect(){//Please execute this on document load, or any event when the select are made available.
var iDropdowns = 10;
var iKey = 0;
for(var i = 1; i <= iDropdowns; ++i){
var sValue = document.getElementById('test' + i).value;
defaultValues['test' + i] = sValue;
}
}
Then, in your function's else, reset the value according to the defaults we have gathered:
else{
alert('Duplicate!');
document.getElementById('test' + i).value = defaultValues['test' + i];
return false;
}
I have written code, i think it can be improved but it works as you asked.
Put it in inside script tag under body so it loads after document.
Put id names of select/dropdown elements in id array.
Take a look: //took me 3 hours O_O
http://jsfiddle.net/techsin/TK9aX/15/
i think i need better strategy to approach programming.