How to create a button on the second page? - javascript

<html>
<head>
<title>The greatest MMO you will ever play</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
function buyStuffWithPoints()
{
var points=prompt("How many points have you earned?");
document.write("<p>Buy your items now and prepare for battle! Choose wisely.<p>" );
document.write("<p><img src = 'sword.jpg'/><p>");
document.write("<p><img src = 'Waterskin.jpg' /><p>");
document.write("<p><img src = 'charm.jpg' /><p>");
document.write("<p><img src = 'Phone.jpg' /><p>");
}
</script>
<input type="button" onclick="buyStuffWithPoints()" value="Start!" />
<div>
<input type="button" onclick="buyStuffWithPoints()" value="Buy Sword(2500)!" />
</div>
</body>
</html>
So currently what happens is when I run it, it prompts me to enter amount of points, then it shows two buttons, "Start!" and "Buy Sword(2500)!". Then after clicking start, the next page shows 4 pictures of the items to buy.
What I want to happen is, after I enter the amount of points, I only want it to show the "Start!" button. Then on the NEXT page, the same page where the pictures show up, I want to show the "Buy Sword" button.
I understand why it's doing this, I just have no idea how to change it. Can anyone help me with this?

You must close your p tags and you should avoid document.write
<html>
<head>
<title>The greatest MMO you will ever play</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
function buyStuffWithPoints() {
var points = prompt("How many points have you earned?");
var html = "<p>Buy your items now and prepare for battle! Choose wisely.</p>"
+ "<p><img src = 'sword.jpg'/></p>"
+ "<div><input type=\"button\" onclick=\"buyStuffWithPoints()\" value=\"Buy Sword(2500)!\" /></div>"
+ "<p><img src = 'Waterskin.jpg' /></p>"
+ "<p><img src = 'charm.jpg' /></p>"
+ "<p><img src = 'Phone.jpg' /></p>"
document.body.innerHTML = html;
}
</script>
<input type="button" onclick="buyStuffWithPoints()" value="Start!" />
</body>
</html>

Related

sending commands/values between pages

im working on a website with 2 pages 1 is the receiver and 2 is the remote basicly you can enter a text on page 2 and once you hit submit page1 starts playing a text to speatch message with the text inut from page2
index.html (aka : page1)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="src/style.css">
</head>
<body>
<h1 id="header"></h1>
<script src="src/script.js"></script>
</body>
</html>
control.html (aka : page2)
<body>
<center>
<form>
<h1 style="color:green">Javatpoint</h1>
<h3> Confirm password Validation Example </h3>
<!-- Enter Password -->
<td> Enter Password </td>
<input type = "password" name = "pswd1"> <br><br>
<button type = "submit" onclick="matchPassword()">Submit</button>
<script>
var pw1 = document.getElementById("pswd1");
function matchPassword() {
<script src="script.js"><script> var x1
}
</script>
script.js of page1
const message = 'Hello world' // Try edit me
// Update header text
document.querySelector('#header').innerHTML = message
// Log to console
console.log(message)
var audio = new Audio('notif.mp3');
audio.play();
var msg = new SpeechSynthesisUtterance();
msg.text = "hallo jeremy";
window.speechSynthesis.speak(msg);
i cant find a way to send the text inside page2 to page 1
There are many ways that you could achieve this, but I'll show you just one. You can easily pass data between pages using query parameters, which are essentially pieces of data appended to the end of a URL.
In order to utilize these, you would need to redirect to your index.html page whenever the user presses the button in the control.html page. Fortunately, this can be done by adding an event listener to your Submit button.
Here is the code below:
control.html
<!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" />
</head>
<body>
<form>
<p>Enter stuff here:</p>
<input type="text" id="text-input" name="text" />
<input type="submit" id="submit-button"></input>
</form>
<!-- continue document... -->
<script src="src/control.js"></script>
</body>
</html>
src/script.js
const queryString = window.location.search;
const queryParams = new URLSearchParams(queryString);
const message = queryParams.get("text");
console.log(message);
// continue file...
src/control.js
const button = document.getElementById("submit-button");
button.addEventListener("click", handleText);
function handleText(event) {
event.preventDefault();
const text = document.getElementById("text-input").value;
const currentURL = window.location.pathname;
const currentDir = currentURL.substring(0, currentURL.lastIndexOf("/"));
window.location.replace(currentDir + "/index.html?text=" + text);
}
Hope this helps!

How can I directly display a value from an excel cell without ActiveX? [duplicate]

I'm trying to create a trigger button that, when pressed, will display a value from an excel cell in alert box or on the page.
below is all I could get, but it doesn't display anything on the page.
update: I managed to do this using ActiveX, but I don't want to use this library for some reasons. Do you have any idea how I could do it?
update code:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.15.6/xlsx.full.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Excel to HTML</title>
</head>
<body>
<p>Press to show</p>
<input type="button" onclick="ReadData(4, 2) ; msgprint()" value="Show" />
<div id="div1">
<script>
function ReadData(cell, row) {
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("mypah/myworkbook.xlsx");
var excel_sheet = excel.Worksheets("Sheet1");
var data = excel_sheet.Cells(cell, row).Value;
document.getElementById("div1").innerText = data;
}
</script>
</div>
<script>
function msgprint() {
alert(document.getElementById("div1").innerText);
}
</script>
</body>
</html>

How can I get search functionality to work when typing in search queries in the input box?

I am making a news style app that uses the newsapi. I want to ask how do I get search functionality to work, how do I get the HTML input box to display the results of what you type in. I have tried a few times to get it to work but can't. Any suggestions appreciated.
HTML
<!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" href="css/style.css">
<title>News App</title>
</head>
<body>
<header>
<h1 class="heading">News</h1>
<form class="searchform" autocomplete="off">
<input class="searchBox" name="search" type="text" >
<button type="submit">Submit</button>
</form>
<li class="newsList"></li>
<script src="js/main.js"></script>
</header>
</body>
JavaScript
const newsList = document.querySelector(".newsList")
const newsImage = document.querySelector(".newsList")
const form = document.querySelector("form.search")
newsImage.innerHTML = ''
newsList.innerHTML= ''
const url = 'https://newsapi.org/v2/everything?' +
'q=${search}&' +
'from=2021-06-02&' +
'sortBy=popularity&' +
'apiKey=****************';
let req = new Request(url);
fetch(req)
.then(function(response) {
return response.json()
}).then((data)=>{
console.log(data)
data.articles.map(article => {
let li = document.createElement('li')
let a = document.createElement('a')
let image = document.createElement('span')
image.innerHTML = `<img src="${article.urlToImage}" >`
a.setAttribute('href', article.url)
a.setAttribute('target','_blank' )
a.textContent = `${article.title}`
li.appendChild(a)
newsList.appendChild(li)
newsImage.appendChild(image)
});
})
function handleSubmit(e){
e.preventDefault()
console.log(e.target)
}
form.addEventListener('submit', handleSubmit)
Okay so I don't have an API key to the news API that you are using but I instead used a free Rick & Morty API to answer your question.
I had to make some alterations to your code in order to get it to work with my API but I added a bunch of comments in the code snippet to hopefully make it make a bit of sense why I made the changes and also how you can change it back to work with your news API. Good luck!
const characters = document.querySelector(".characters");
const searchInput = document.querySelector("#search");
characters.innerHTML = "";
// We also changed this here to include the actual act of fetching the data - you would instead do your news fetch here.
function handleClick(e) {
let url = "https://rickandmortyapi.com/api/character/";
// This here maps a HTMLCollection into a JavaScript array and then removes previous children if they exist,
// this is to clear the list items prior to a new search.
if (characters.children.length > 0)
Array.from(characters.children).forEach((child) => child.remove());
// If we provide a search input include it in the URL - note the only search we can do here is for pages so the input is now a number.
// This is where you would instead change your news URL and append the "searchInput.value" into the "search section" like so:
//
// const url =
// "https://newsapi.org/v2/everything?" +
// `q=${searchInput.value}&` +
// "from=2021-06-02&" +
// "sortBy=popularity&" +
// "apiKey=****************";
//
// Note that in order to use a variable you need backticks as your quote delimeter. See like `${variable}` instead of '' or "".
if (searchInput.value)
url =
"https://rickandmortyapi.com/api/character/" +
`?page=${searchInput.value}`;
let req = new Request(url);
fetch(req)
.then(function (response) {
return response.json();
})
.then((data) => {
console.log(data);
// I removed your image mapping here because I had no image from this free Rick and Morty API but I hope you get the idea.
data.results.map((character) => {
let li = document.createElement("li");
let a = document.createElement("a");
a.setAttribute(
"href",
"https://rickandmortyapi.com/api/character" + `/${character.id}`
);
a.setAttribute("target", "_blank");
a.textContent = `${character.name}`;
li.appendChild(a);
characters.appendChild(li);
});
});
}
<!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" />
<!-- I removed this because I had no css file -->
<!-- <link rel="stylesheet" href="css/style.css" /> -->
<title>Test App</title>
</head>
<body>
<header>
<h1 class="heading">Test</h1>
<form class="searchform" autocomplete="off">
<!-- <input id="search" class="searchBox" name="search" type="text" /> -->
<!-- Because my search in the free API could only handle numbers I changed the type here -->
<!-- You will want to change that back to the above commented out text field -->
<input id="search" class="searchBox" name="search" type="number" />
<!-- Instead of using prevent default I changed the action here to be the onclick of the button -->
<!-- That fires off our "handleClick()" method that lives in our main.js file -->
<button type="button" onclick="handleClick()">Submit</button>
</form>
<div class="characters"></div>
<script src="main.js"></script>
</header>
</body>
</html>

Passing and getting an array displayed as html text

I'm passing an array of strings to be displayed as html text inside a
my_arr = ["PRODUCT", "SHAMPOO1", "SHAMPOO2", "SHAMPOO3", "SHAMPOO1"]
which is displayed as :
PRODUCT, SHAMPOO1, SHAMPOO2, SHAMPOO3, SHAMPOO1.
What I want to do is make these clickable. And when I click on one of these words I want that word to be displayed below it.
What's the cleanest way to do this?
Passing the array in the <a> tag isn't working for me.
you can add it to the DOM, then loop your array to the li under ul
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<div id="products"></div>
<body>
<script>
var my_arr = ["PRODUCT", "SHAMPOO1", "SHAMPOO2", "SHAMPOO3", "SHAMPOO1"];
var str = "<ul>";
my_arr.forEach(function (product) {
str += "<li> <a href='/'>" + product + "</a> </li>";
});
str += "</ul>";
document.getElementById("products").innerHTML = str;
</script>
</body>
</html>

InnerHTML- fetching from script

I am trying to display random numbers from 1 to 7. I do not want them to repeat and I want to display every number. I've written my JS code inside script tag. I want to get a random number whenever button is clicked, instead I'm getting error
Uncaught TypeError: Cannot set property 'innerHTML' of null
at grandom (fe.html:48)
at HTMLButtonElement.onclick (fe.html:25)
Below is my code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Goplan Project Selection</title>
<link rel="canonical" href="https://getbootstrap.com/docs/4.1/examples/sign-in/">
<!-- Bootstrap core CSS -->
<link href="https://getbootstrap.com/docs/4.1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="jumbotron">
<div class="text-center">
<img src="cissoiree.jpg" width="80px" height="80px">
<h1 style="text-size:300em">Go-Plan</h1></div></div>
<div style="padding-top:20px;" class="text-center">
<button class="btn-lg btn-primary" onclick="grandom()">Click!</button>
<p id="demo"><p>
</div>
<script type="text/javascript">
function grandom()
{
var q=[2,3,1,5,4,7,6];
var x=7;
var i;
x=q.length;
var random;
while(1)
{
random = Math.floor(Math.random()*x);
if(random<=q.length)
break;
}
document.write("<br>");
document.write("Question No : " + q[random] );
if(q.length!=1)
<!--document.write("<input type=button value=click here onclick=grandom();><br>");-->
document.getElementById("demo").innerHTML = q[random];
q.splice(random,1);
document.write("<br>");
}
</script>
</body>
</html>
After document.write(...); there is no other elements in the page expect the passed text.
It is why when you trying to find then document.getElementById("demo") it's cannot find, and return null. (then throw error, when you trying to access its innerHTML)
If you trying to append something to the page you should use document.body.innerHTML += "...".
About the algorithm itself - you can use:
[1,2,3,4,5,6,7].sort(function() { return .5 -Math.random();});
It will shuffle the array randomly.
Your document.write(..) is breaking it.
You can try:
document.body.innerHTML += '<br />';
document.getElementById("demo").innerHTML = `Question No : ${q[random]}`;
document.body.innerHTML += '<br />';

Categories

Resources