I'm creating multiple random generators. Once the first random generator selects a particular name the second will overide the first random generator and display the second random gernerators selection.
Here is what I have so far:
<!doctype html>
<html>
<head>
<script>
function postmessage() {
var firstnames = ["John", "Jacob", ];
var firstname = firstnames[Math.floor(Math.random() * firstnames.length)];
function pickAnother(John) {
if (John != firstnames) {
run(sndnames);
}
}
pickAnother (firstnames);
var sndnames = ["Eric", "Conroy", ];
var sndname = sndnames[Math.floor(Math.random() * sndnames.length)];
</script>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<input type="button" value="Get Recruit" onclick="postmessage();" />
<div id="recruit"></div>
</body>
</html>
I managed to get an alart message from another code, but I would like to display the sndnames like the firstnames.
Related
I'm trying to make a list of buttons and their names into an array in javascript?
I heave searched the internet for help but not found anything so far. The div with the name "apps" is where I'm trying to grab from and the array inside of the if statement in the javascript code is what I'm to to replace with the array.
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="clicker.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<title>Vairoon's clicker</title>
</head>
<body>
<button onclick="smnPlayer()">Get new player</button>
<p>Players per click: <span id="PPC">1</span></p>
<p>Players: <span id="players">0</span></p>
<p>New players per second: <span id="PPS">0</span></p>
<div class="upgrade">
<p>Upgrade your clicker game: <span id="upgCost">400</span></p>
<button id="upgrade">Upgrade clicker</button>
</div>
<div id="apps" name="apps"> <!-- The div I'm trying to grab from-->
<button>Obj1</button>
<button>Obj2</button>
</div>
<script ="clicker.js"></script>
</body>
</html>
Javascript code:
var players=0;
var PPS=0;
var PPC=1;
var upgradeCost=400;
var apps = ["New buildings","More upgrades","Adverts","More minigames"]
var basecosts = [0,20,100,1500,15000]
function getEl(elID) {
return document.getElementById(elID);
}
function smnPlayer() {
players+=PPC;
document.getElementById("players").innerHTML=players;
}
getEl("upgrade").onclick = function upgrade() {
if (players>=upgradeCost) {
players-=upgradeCost;
upgradeCost=upgradeCost*3;
PPC=Math.ceil(PPC*2);
PPS=PPS*2;
getEl("players").innerHTML=players;
getEl("upgCost").innerHTML=upgradeCost;
getEl("PPC").innerHTML=PPC;
getEl("PPS").innerHTML=PPS;
}
}
setInterval(() => {
if (players>=upgradeCost) {
getEl("upgrade").style.display="block";
} else {
getEl("upgrade").style.display="none";
}
for (let index = document.querySelectorAll('#apps').length; index < basecosts.length+1; index++) {
if (players>=basecosts[index]) {
if (array.includes(apps[index])){}else{ //the "array" is what to replace with the array
var button = document.createElement("BUTTON");
button.innerHTML = apps[index];
document.getElementById("apps").appendChild(button);
}
}
}
},10)
If you still don't understand what I'm trying to do, here's another explanation:
I want the code to go from
<div>
<button>Obj1</button>
<button>Obj2</button>
</div>
to
["Obj1","Obj2"]
Oh and a question if you can answer too, how do I add break line between the items I'm creating just with js?
For your simplified example:
myArray = Array.from(document.querySelectorAll("div button")).map(
function(b) {
return b.innerText;
}
);
console.log(myArray);
//add a line break:
document.querySelector("div").insertBefore(document.createElement("br"),document.querySelectorAll("div button")[1]);
<div>
<button>Obj1</button>
<button>Obj2</button>
</div>
I'm trying to make a random sequence triggered by mouse click, and track how many times a user would click on the images. Could anyone help me with that? Thanks!
Below are my code that are pulling images randomly:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>The Door Moment</title>
<script type="text/javascript">
function changePic()
{
var num = Math.ceil(Math.random()*9);
document.getElementById("p").src = num + ".jpg";
}
function buttonclick() {
document.getElementById("p").value++;
}
</script>
</head>
<body>
<p align="center"><img src = "1.jpg" id = "p" width="400px" height="600px" onclick="changePic()" /></p>
</div>
</body>
Assume you start your image sequence from 1, you can use a counter to count your image click times.
When image element is clicked, buttonclick function will track how many times user has clicked on the image. And then change your current image sequence number which will show a different image.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>The Door Moment</title>
<script type="text/javascript">
const counter = {};
let num = 1;
function changePic()
{
num = Math.ceil(Math.random()*9);
document.getElementById("p").src = num + ".jpg";
}
function buttonclick() {
counter[num] = (counter[num] || 0) + 1;
console.log(counter)
//if you want to show current count for the sequence, you can use console.log(counter[num])
changePic()
}
</script>
</head>
<body>
<p align="center"><img src = "1.jpg" id = "p" width="400px" height="600px" onclick="buttonclick()" /></p>
</div>
</body>
try make clickCounter object with a key equal to the picture number and better use onclickmethod in JS but not in html
let num = 1;
const clickCounter = {};
const randomPic = document.getElementById('randomPic')
randomPic.onclick = function(){
clickCounter[num] = (clickCounter[num] || 0) + 1;
changePic();
console.log(clickCounter); // if you need
}
function changePic() {
num = Math.ceil(Math.random()*9);
randomPic.src = num + ".jpg";
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>The Door Moment</title>
</head>
<body>
<p align="center"><img src = "1.jpg" id = "randomPic" width="400px" height="600px"/></p>
</body>
</html>
My purpose is to check if value entered by user in the input field is already available in an array stored in the localstorage. If yes, print the array if not add the new value in the storage. I am getting my array back on button click but the code isn't working correctly. The output is:
["hh", "try", "vogue", "vogue", "try2", "try2", "try2", "try2"]
Above are the entered values which are getting added repetitively. I know it's a stupid issue but have least experience with handling arrays in localstorage. Any help would be appreciated. (I tried the solutions provided in similar questions on stackoverflow but no luck)
<html class=" reevoomark_ATY">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Special Offers</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="crossorigin="anonymous"></script>
</head>
<body>
<input id="coupon"> <button style="width:50px;padding:10px;background:grey;height:30px;border:1px solid grey" id="button">Apply</button>
<input id="stored">
<script>
var coupons = ['hh'];
var storedNames;
localStorage.setItem("coupons", JSON.stringify(coupons));
$('#button').on('click', function(){
storedNames = JSON.parse(localStorage.getItem("coupons"));
var enteredValue = $('#coupon').val();
for(i=0; i <storedNames.length; i++) {
if(enteredValue === storedNames[i]) {
console.log("value Exist!!");
console.log(storedNames[]);
}
else {
console.log("in else");
coupons.push(enteredValue);
localStorage.setItem("coupons", JSON.stringify(coupons));
storedNames = JSON.parse(localStorage.getItem("coupons"));
}
}
});
</script>
</body>
</html>
You would like to push the names if it doesn't exist in the stored names. Refer attached code.
<html class=" reevoomark_ATY">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Special Offers</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="crossorigin="anonymous"></script>
</head>
<body>
<input id="coupon"> <button style="width:50px;padding:10px;background:grey;height:30px;border:1px solid grey" id="button">Apply</button>
<input id="stored">
<script>
var coupons = ['hh'];
localStorage.setItem("coupons", JSON.stringify(coupons));
$('#button').on('click', function(){
var storedNames = JSON.parse(localStorage.getItem("coupons"));
var enteredValue = $('#coupon').val();
if (storedNames.includes(enteredValue)) {
console.log("value Exist!!");
console.log(storedNames);
} else {
console.log("in else");
storedNames.push(enteredValue);
localStorage.setItem("coupons", JSON.stringify(storedNames));
}
});
</script>
</body>
</html>
I am having trouble kicking NaN out of array "free_time_integers" below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>parse testing</title>
</head>
<body>
<textarea name="" id="txt1" cols="30" rows="10">
1139
2938
3828
112
</textarea>
<script>
var free_time_hours = document.getElementById('txt1')
// free_time_hours.addEventListener("blur", free_time_console)
// Parse the free time values into times
// convert textarea into array
var breaker_array = free_time_hours.value.split(/\n/)
console.log("array freshly split")
console.log(breaker_array)
//convert array each element to a string
let free_time_integers = breaker_array.map(function(obj) {
return parseInt(obj)
})
// get the NaN out of the array
function remove_false(arr) {
arr.filter(Boolean)
}
remove_false(free_time_integers)
console.log("after map-parseInt and filter-true")
console.log(free_time_integers)
</script>
</body>
</html>
I've also tried using a for loop and if statement to check if any item === NaN but that didn't seem to work either. I read in another thread that NaN doesn't equal itself so that may be why. Is there any way to eliminate the NaN values?
You can use isNaN to check if it something a NaN and the Array.filter function to keep the elements that is not NaN. Another issue is that you have to store the results somewhere. So, your final code will look like the following:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>parse testing</title>
</head>
<body>
<textarea name="" id="txt1" cols="30" rows="10">
1139
2938
3828
112
</textarea>
<script>
var free_time_hours = document.getElementById('txt1')
// free_time_hours.addEventListener("blur", free_time_console)
// Parse the free time values into times
// convert textarea into array
var breaker_array = free_time_hours.value.split(/\n/)
console.log("array freshly split")
console.log(breaker_array)
//convert array each element to a string
let free_time_integers = breaker_array.map(function(obj) {
return parseInt(obj)
})
// get the NaN out of the array
// my implementation here...
function remove_false(arr) {
return arr.filter(e => !isNaN(e));
}
// assign it to a variable
var filtered_arr = remove_false(free_time_integers)
console.log("after map-parseInt and filter-true")
console.log(filtered_arr)
</script>
</body>
</html>
filter returns a new array, you need to reassign it to free_time_integers
function remove_false(arr) {
return arr.filter(Boolean)
}
free_time_integers = remove_false(free_time_integers)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>parse testing</title>
</head>
<body>
<textarea name="" id="txt1" cols="30" rows="10">
1139
2938
3828
112
</textarea>
<script>
var free_time_hours = document.getElementById('txt1')
// free_time_hours.addEventListener("blur", free_time_console)
// Parse the free time values into times
// convert textarea into array
var breaker_array = free_time_hours.value.split(/\n/)
console.log("array freshly split")
console.log(breaker_array)
//convert array each element to a string
let free_time_integers = breaker_array.map(function(obj) {
return parseInt(obj)
})
// get the NaN out of the array
function remove_false(arr) {
return arr.filter(Boolean)
}
free_time_integers = remove_false(free_time_integers)
console.log("after map-parseInt and filter-true")
console.log(free_time_integers)
</script>
</body>
</html>
I have a hidden input on my page like so:
<input type="hidden" name="required" value="name,town,tel,email">
As people fill in it's associated form, certain other fields become required (i.e. State becomes required when choosing "USA" from a Country dropdown).
I have two functions, one named addToRequiredFields() and one named removeFromRequiredFields() which fire as USA is selected/de-selected, however the removal one doesn't seem to be working, and I can't figure out why.
function addToRequiredFields(string) {
var required = $('input[name=required]').val();
required += ',' + string;
$('input[name=required]').val(required);
}
function removeFromRequiredFields(string) {
var required = $('input[name=required]').val();
required.replace(',' + string, '');
$('input[name=required]').val(required);
}
The function is called at .on('change') of the Select dropdown.
Though Its not a proper way to validate controls based on input value , I made a script for you .
function addToRequiredFields(string) {
var required = $('input[name=required]').val();
fieldsArray = required.split(",")
fieldsArray.push(string)
$('input[name=required]').val(fieldsArray.join());
}
function removeFromRequiredFields(string) {
var required = $('input[name=required]').val();
fieldsArray = required.split(",")
fieldsArray = fieldsArray.filter(function(item) {
return item !== string
})
$('input[name=required]').val(fieldsArray.join());
}
console.log($('input[name=required]').val())
addToRequiredFields("age")
console.log($('input[name=required]').val())
removeFromRequiredFields("name")
console.log($('input[name=required]').val())
removeFromRequiredFields("tel")
console.log($('input[name=required]').val())
addToRequiredFields("name")
console.log($('input[name=required]').val())
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="hidden" name="required" value="name,town,tel,email">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
Use the below login inside yourremove function.removeFromRequiredFields
//var requiredArr = $('input[name=required]').attr('value');
var requiredArr = "name,town,tel,email".split(',');
var rmvIndex = requiredArr.indexOf("tel")//"tel" is your string to be removed
var newArr = requiredArr.splice(rmvIndex, 1);
$('input').attr('value', newArr.join(','))// set value attribute after removing that string