I'm creating a little script to try and search for an element in the array based on input.
var modulo = document.getElementById("modulo").value;
var link = [
"http://www.forumfree.it/",
"http://www.forumcommunity.net/",
"http://www.blogfree.net/",
];
if(modulo.indexOf(link) > -1) {
alert("Your site is:" + modulo);
}
else {
alert("Sorry, I don't found:" + modulo)
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Search element in array</title>
</head>
<body>
<input type="text" id="modulo" class="form">
</body>
</html>
Anyone can explain to me how to do that (if there's another way to do it better, inform me), and why my code doesn't run? Thanks!
Code explanation: I've used var modulo to contain the value of the input. Then I've created a variable to contain the link. Then if-else statement and indexOf to search and find it.
Thanks, the code solution is: https://plnkr.co/edit/bDt4n34KBFAvZrSWmb4a?p=preview
You can try with this plunker https://plnkr.co/edit/bDt4n34KBFAvZrSWmb4a?p=preview it used event trigger to have a button to search website :
<button onclick="myFunction()">Search</button>
and I wrote your code into a function.
I hope this will help you
The final state :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<input type="text" id="modulo" class="form">
<button onclick="myFunction()">Search</button>
</body>
var link = [
"http://www.forumfree.it/",
"http://www.forumcommunity.net/",
"http://www.blogfree.net/",
];
function myFunction() {
var input = document.getElementById("modulo");
var results = [];
for(var i = 0; i < link.length; i++) {
if(link[i].indexOf(input.value) > -1) {
results.push(link[i]);
}
}
if(results.length == 1) {
alert("Your site is:" + results[0]);
}
else if (results.length > 1){
alert("Sorry, your search return more than one result:" + results)
}
else {
alert("Sorry, I don't found:" + input.value)
}
}
You have
if(modulo.indexOf(link) > -1)
but I think that it should be
if(link.indexOf(modulo) > -1)
Assuming that modulo is a single string element, this will search the link array for that element and return the index of that element.
I think you were on the right track. You just need a few things:
a button to initiate the search
put your code in a function so you can call it
you want to search the array link for the value of the input modulo
function findIt() {
var modulo = document.getElementById("modulo").value;
var link = [
"http://www.forumfree.it/",
"http://www.forumcommunity.net/",
"http://www.blogfree.net/",
];
if (link.indexOf(modulo) > -1) {
alert("Your site is:" + modulo);
} else {
alert("Sorry, I don't found:" + modulo)
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Search element in array</title>
</head>
<body>
<input type="text" id="modulo" class="form">
<input type="button" onclick="findIt()" value="find it">
</body>
</html>
function runscript() {
var modulo = document.getElementById("modulo").value;
var link = [
"http://www.forumfree.it/",
"http://www.forumcommunity.net/",
"http://www.blogfree.net/",
];
var found = false;
for(var i = 0; i < link.length; i++) {
if (link[i].indexOf(modulo) > -1) {
alert("Your site is:" + link[i]);
found = true;
}
}
if (!found) {
alert("Sorry, I don't found:" + modulo)
}
}
And the HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Search element in array</title>
</head>
<body>
<input type="text" id="modulo" class="form">
<input type="button" onclick="runscript()" value="search" />
</body>
</html>
You will need to press button for search
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 create a word game that will choose a random item from a list but some of the items have different weights so they show up less often. I want the function to be called once the user presses a HTML button. I have the code working fairly well right now (to the console). My question is how can I get the output from the function into the html web page. If anyone could help me with this, it would be a huge help.
Here's my code:
var item = {
'apple':10,
'banana':10,
'orange':10,
'grapes':1,
}
function testGame(input) {
var array = [];
for(var item in input) {
if(input.hasOwnProperty(item) ) {
for(var i=0; i<input[item]; i++ ) {
array.push(item);
}
}
}
return array[Math.floor(Math.random() * array.length)];
}
console.log(testGame(item));
I have some HTML code too, just don't know where or how to write the button code properly to produce the outcome I'm looking for.
Here's the HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Randomizer Game</title>
</head>
<body>
<h1>Game</h1>
<script src="index.js"></script>
<button onclick="testGame();">Test</button>
</body>
</html>
You can make new function where you can call it on button just like you called it with console.log:
<button onclick="start();">Test</button>
and call your randomizing function inside:
function start() {
testGame(item)
}
Then inside function testGame don't use return, just save random word result in variable and print it in HTML:
var result = array[Math.floor(Math.random() * array.length)];
console.clear();
console.log(result);
document.getElementById("result").innerHTML=result;
I have added div result in HTML:
<div id="result"></div>
EXAMPLE SNIPPET:
var item = {
'apple': 10,
'banana': 10,
'orange': 10,
'grapes': 1,
}
function testGame(input) {
var array = [];
for (var item in input) {
if (input.hasOwnProperty(item)) {
for (var i = 0; i < input[item]; i++) {
array.push(item);
}
}
}
var result = array[Math.floor(Math.random() * array.length)];
console.clear();
console.log(result);
document.getElementById("result").innerHTML=result;
}
function start() {
testGame(item)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Randomizer Game</title>
</head>
<body>
<h1>Game</h1>
<div id="result"></div>
<script src="index.js"></script>
<button onclick="start();">Test</button>
</body>
</html>
Use getElementById to get an element by id, for this I gave your button an id. With addEventListener you can add an event (here: click) to be call a function.
Doing here your randomizing. Get the element where you want the output again with getElementByIdand add with textContent your answer to it.
const ITEMS = {
'apple':10,
'banana':10,
'orange':10,
'grapes':1,
}
document.getElementById('btn').addEventListener('click', function testGame() {
var array = [];
for(var item in ITEMS) {
if(ITEMS.hasOwnProperty(item) ) {
for(var i=0; i<ITEMS[item]; i++ ) {
array.push(item);
}
}
}
document.getElementById('item').textContent = array[Math.floor(Math.random() * array.length)];
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Randomizer Game</title>
</head>
<body>
<h1>Game</h1>
<button id='btn'>Test</button>
<div id='item'></div>
</body>
</html>
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 have just started learning Javascript, and I attempted to write code for hit counter for a webpage using Javascript. I know that we have to use cookies to get the correct number and use PHP to modify data stored in servers. But could you please debug this for me ? I'm getting the output as "The number of visitors is: NaN"
This is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<p>The number of visitors is : <span id="cntr">0</span></p>
</div>
<script>
function counter_fn() {
var counter = document.getElementById("cntr");
var count = 0;
count = counter.value;
count = count + 1;
counter.innerHTML = count;
}
window.onload = counter_fn;
</script>
</body>
</html>
You are trying to get the valuefrom a span element, which is wrong.
Your counter.value is undefined so it will give you the wrong answer.
You can get the 0 from the span by using document.getElementById("cntr").innerHTML. But the value returned is in string. So you need to do parseInt to convert it into integer and only then your addition will give you the correct value.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<p>The number of visitors is : <span id="cntr">0</span></p>
</div>
<script>
function counter_fn() {
var counter = document.getElementById("cntr");
var count = 0;
count = parseInt(counter.innerHTML);
count = count + 1;
counter.innerHTML = count;
}
window.onload = counter_fn;
</script>
</body>
</html>
You need to use parseInt
<script>
function counter_fn(){
var counter = document.getElementById("cntr");
var count = 0;
count = parseInt(counter.value);
count = count+1;
counter.innerHTML = parseInt(count);
}
window.onload = counter_fn;
</script>
UPDATE
As #Anurag Singh Bisht commented, you cannot get value from a span element . So to get value from <span> you need to use $('span').text();
<html>
<body>
<div id="cntr">
The number of visitors is :
<span>0</span>
</div>
<script>
function counter_fn(){
var counter = $('#cntr span').text(); // geting value from span
var count = 0;
count = parseInt(counter.value);
count = count+1;
counter.innerHTML = parseInt(count);
}
window.onload = counter_fn;
</script>
</body>
</html>
You need to parse the string to an integer and you need to get the innerHTML.
<script>
function counter_fn(){
var counterElement = document.getElementById("cntr")
var counterNumber = parseInt(counterElement.innerHTML)
counterNumber = counterNumber + 1
counterElement.innerHTML = counterNumber
}
window.onload = counter_fn;
</script>
The correct way to do it would be storing this value somewhere else, like localStorage and reading it from there. You are not supposed to read your own HTML to update the value. HTML elements are supposed to be results, not your input.
var counterNumber = 1
if (localStorage.getItem("count")) {
counterNumber = parseInt(localStorage.getItem("count")) + 1
}
else {
localStorage.setItem("count", counterNumber)
}