My page keeps on reloading after my fetch request is complete. I don't want the page to reload after I submit the form. Can anyone help out as to why even after using e.preventDefault() I get that behavior? Also can you suggest better formatting tips for JS as I'm a beginner and would like your input. I'm fetching the data from a fake REST API made using json-live-server
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="styles.css">
<title>Document</title>
</head>
<body class="body">
<h1> Vaccination Centers</h1>
<div id='app'>
<form id='form'>
<input type="text" id='enrollment' />
<input type='text' id='session' />
<button type="submit">submit</button>
</form>
</div>
<script type="module" src="main.js"></script>
</body>
</html>
JS
let listArray
function getCenters () {
fetch ('http://localhost:3001/students')
.then(
response => response.json()
)
.then(data => {
listArray = data
console.log(listArray)
})
};
function init () {
getCenters()
const form = document.getElementById('form')
form.addEventListener('submit', (e) => validate(e))
}
function validate (e) {
console.log(e)
e.preventDefault()
let enrollment = document.getElementById('enrollment').value
let student = listArray.find(s => s.enrollment.toString() === enrollment.toString())
fetch ('http://localhost:3001/students/' + student.id, {
method: 'PATCH',
headers: {
'Content-type': 'application/json; charset=UTF-8' // Indicates the content
},
body: JSON.stringify({ paidFee: true })
}).then(document.getElementById('app').innerHTML = 'HELLO BITCHES')
}
window.onload = init
We can all agree that e.preventDefault() placed at the first line ⃰ in the event handler (aka validate(e)) will stop the default browser behavior of a <form> when a "submit" event is triggered on it. The behavior OP is observing is the destructive overwriting of the following:
.then(document.getElementById('app').innerHTML = 'HELLO BITCHES')
Just remove the above and you shouldn't have what appears as a page reload, but if you must say, "HELLO" to the bitches, use .insertAdjacentHTML() instead:
.then(document.getElementBYId('app').insertAdjacentHTML('beforeBegin', 'HELLO BITCHES'))
The following example has an event handler for the "submit" (submitter(e)) and "click" (clicker(e)) events. If button#A is clicked, .innerHTML is used and if button#B is clicked, .insertAdjacentHTML() is used. There is also a logger function (eventLogger(e)) which will log:
type of event........................................e.type
event listener #id............................e.currentTarget
button #id..........................................e.target.id (from 'click' event)
if default was prevented or not.....e.defaultPrevented
⃰actually it's console.log() at that position but there's no difference in this context
Best viewed in Full Page mode
document.forms[0].addEventListener('submit', submitter);
document.querySelectorAll('button').forEach(node => node.addEventListener('click', clicker));
function submitter(e) {
e.preventDefault();
let ID = this.elements.AB.value;
const APP = document.getElementById('app');
switch (ID) {
case 'A':
APP.innerHTML = 'HELLO BITCHES - #app is gutted by .innerHTML - everything within #app is overwritten';
break;
case 'B':
const htmlString = 'HELLO BITCHES - this is added in front of #app - nothing is overwritten bitches';
APP.insertAdjacentHTML('beforeBegin', htmlString);
break;
default:
break;
}
eventLogger(e);
};
function clicker(e) {
document.forms[0].AB.value = e.target.id;
};
function eventLogger(e) {
let ID = e.target.elements.AB.value;
console.clear()
let log = 'Event Type: ' + e.type + '\nEvent Listener ID: ' + e.currentTarget.id + '\nButton ID: ' + ID + '\nDefault Prevented: ' + e.defaultPrevented;
console.log(log);
};
body {
padding: 8px;
font: 1ch/1 Consolas;
}
h1 {
font-size: 1.75ch/1;
}
#app {
margin: 8px;
padding: 20px;
outline: 3px dashed blue;
}
form {
padding: 20px;
outline: 3px dotted red
}
input {
display: inline-block;
width: 15ch;
}
button {
display: inline-block;
width: 6ch;
cursor: pointer;
}
p {
display: inline-block;
}
p:first-of-type {
color: blue;
}
p:last-of-type {
color: red;
}
code {
font-weight: bold;
color: #ab00ef;
}
/* SO Console Display - Right Side Column */
.as-console-wrapper {
width: 50% !important;
max-height: 100%;
margin: 0 0 25% 50%;
font-size: 0.8ch/1;
font-variant: normal;
}
.as-console-row.as-console-row::after {
content: '';
padding: 0;
margin: 0;
border: 0;
width: 0;
}
<!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>
<body class="body">
<h1>Vaccination Centers</h1>
<p>Blue dashed outline is <code>#app</code></p>
<p>Red dotted outline is <code>#form</code></p><br>
<div id='app'>
<form id='form'>
<input type="text" id='enrollment'>
<input type='text' id='session'>
<button id='A'>A</button>
<button id='B'>B</button>
<input id='AB' type='hidden'>
</form>
</div>
</body>
</html>
There were a few bits that needed some attendence:
In your original script you used an asynchronous fetch to define the variable listArray. Unfortunately you did not wait for the value to be put into that variable but continued straight away. This "awaiting" can only happen in an asynchronous function. Therefore:
I created an async function as this makes it much easier to process promises with await inside.
The first one fills listArray with all the registered students for comparison with an entered name
The comparison needs to be done on enrollment.value.trim().toLowerCase() (there is no .toString() involved)
If the name was found, a second fetch() command is sent, "PATCHing" the new information to the server
The return data from the server is then displayed in JSON format under the "success message".
const api='http://jsonplaceholder.typicode.com/users/';
document.getElementById('form').addEventListener("submit",validate);
async function validate(e) {
e.preventDefault();
const listArray=await fetch(api).then(r=>r.json());
let student= listArray.find(s=>s.username.toLowerCase()===enrollment.value.trim().toLowerCase())
if (student) {
const d = await fetch(api+student.id, {method: 'PATCH',headers: {'Content-Type': 'application/json'},body: JSON.stringify({paidFee:true})}).then(r=>r.json());
document.getElementById('app').innerHTML = '<div>HELLO BITCHES</div><pre>'+JSON.stringify(d,null,2)+'</pre>';
} else console.log("This student does not exist in our list: "+listArray.map(s=>s.username).join(" "));
}
<h1> Vaccination Centers</h1>
<div id='app'>
<form id='form'>
<input type="text" id='enrollment' value="Bret">
<input type='text' id='session'>
<button type="submit">submit</button>
</form>
</div>
Related
I am looking to create a standalone webserver using the Wemos D1 Mini Lite (this is the only wifi microcontroller I have and cant afford a different one atm).
I know SPIFFS works with ESP32 chips, but can I use it with ESP8285 chips?
Looking to have HTML and CSS for the webserver, with JS scripts to run functions (At the moment only functionality is turning LEDs off and on), all uploaded to the Wemos and run from that.
HTML CODE
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./skeleton.css">
<link rel="stylesheet" href="./theme.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class = "mainDiv border" >
<div class = "headingDiv border">
<h3 id = "Header"> LED ON AND OFF </h3>
</div>
<div class = "checkmarkDiv border">
<div class = "row">
<label for ="colour_red">RED LED</label>
<input type = "checkbox" id = "colour_red">
</div>
<div class = "row">
<label for ="colour_yellow">YELLOW LED</label>
<input type = "checkbox" id = "colour_yellow">
</div>
<div class = "row">
<label for ="colour_green">GREEN LED</label>
<input type = "checkbox" id = "colour_green">
</div>
</div>
<div class = "buttonDiv border">
<button class = "button-primary" id = "button_ToggleLED"> Turn LED: ON </button>
</div>
</div>
</body>
<script src = "./mainJS.js"></script>
</html>
JS CODE
const button_LED = document.getElementById( "button_ToggleLED" )
const cb_red = document.getElementById ( "colour_red" )
const cb_yellow = document.getElementById( "colour_yellow" )
const cb_green = document.getElementById( "colour_green" )
let clickCheck = false
button_LED.addEventListener( "click", (event) => {
//consoleLEDStatus()
if (clickCheck) {
button_LED.innerHTML = "Turn LED: ON"
turnOFFLED()
}
else if (!clickCheck) {
button_LED.innerHTML = "Turn LED: OFF"
turnONLED()
}
clickCheck = !clickCheck
})
// A quick function you can run to check in dev console the status of LED
function consoleLEDStatus() {
console.log(`LED Status:
RED: ${cb_red.checked}
YELLOW: ${cb_yellow.checked}
GREEN: ${cb_green.checked}`)
}
function turnOFFLED() {
// Insert function to turn off LED
}
function turnONLED() {
// Insert function to turn on LED
}
CSS CODE
/* Test class for checking Div borders. Uncomment to see them*/
/*
.border{
border: black 2px solid;
}
*/
.mainDiv{
margin-left: 20%;
margin-right: 20%;
padding: 10px;
}
.checkmarkDiv{
padding: 10px;
}
.buttonDiv{
padding: 10px;
}
.headingDiv{
padding: 10px;
}
#Header{
}
#button_ToggleLED{
width: 200px;
float: center;
}
SPIFFS has been replaced with LittleFS (Little File System) and it works on EPS8266, See LittleFS for more details.
The code example for using LittleFS to serve webpage can be found at FSBrowser example. It is a quite comprehensive example, you probably only need to implement part of it.
I'm using the AniList API to make some requests and load the data.
The first request I'm doing it works well (note that the page loads with some covers), but when I'm using the search button I get failed to fetch. Because the first time worked, but not when modifying the query, I thought that might be wrong in the way I was modifying it, but after a double check, I only modify variables.search and then I proceed to do the same as the first time I'm loading the page, so I don't really know why it's failing. I also tried to modify the first query, when the page is loading, and it works, so I don't think it has anything to do with the API.
Here's the code
const resultsEl = document.getElementById("container-results");
const submitBtnEl = document.getElementById("submit-button");
const inputTxtEl = document.getElementById("input-txt")
var query = `
query ($id: Int, $page: Int, $perPage: Int, $search: String) {
Page (page: $page, perPage: $perPage) {
pageInfo {
total
currentPage
lastPage
hasNextPage
perPage
}
media (id: $id, search: $search) {
id
title {
romaji,
english,
}
type
coverImage {
large
}
}
}
}
`;
var variables = {
search: "Pokemon",
page: 1,
perPage: 5000
};
var url = 'https://graphql.anilist.co',
options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query: query,
variables: variables
})
};
fetch(url, options).then(handleResponse)
.then(handleData)
.catch(handleError);
function handleResponse(response) {
return response.json().then(function (json) {
return response.ok ? json : Promise.reject(json);
});
}
function handleData(data) {
processData(data);
}
function handleError(error) {
console.error(error);
alert('Error, check console');
}
function processData(data) {
let processedData = [];
queryResults = data.data.Page.media;
for (let i = 0; i < queryResults.length; i++) {
let obj = {}
obj.title = queryResults[i].title.romaji;
obj.image = queryResults[i].coverImage.large;
processedData.push(obj);
}
for (let i = 0; i < processedData.length; i++) {
let img_div = document.createElement("div");
img_div.className = "cover-Image"
img_div.innerHTML += processedData[i].title;
img_div.innerHTML += "<img width=250 height=400 src=" + processedData[i].image + ">";
resultsEl.appendChild(img_div);
}
}
submitBtnEl.addEventListener("click", () => {
const userQuery = inputTxtEl.value;
if (userQuery !== "") {
variables.search = userQuery;
options.body = JSON.stringify({
query: query,
variables: variables
})
fetch(url, options).then(handleResponse)
.then(handleData)
.catch(handleError);
}
else {
resultsEl.innerHTML = "";
}
})
* {
box-sizing: border-box;
margin: 0;
padding: 0;
background-color: black;
}
body {
background-color: black;
}
.container-results {
display:flex;
flex-wrap: wrap;
justify-content: center;
}
.cover-Image{
padding: .3em;
margin: .1em;
width:300px;
color:white;
}
img{
margin: 0.5em;
}
#media (min-width: 960px) {
#nani{
width: 500px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Working with api's example</title>
<!--Bootstrap related things-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
<link rel="stylesheet" href="css/styles.css">
<script src="js/script.js" defer></script>
</head>
<body>
<!--NAVBAR-->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Manga search</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<form class="form-inline my-2 my-lg-0 mx-auto">
<input class="form-control mr-sm-2" id="input-txt" type="search" placeholder="Place title" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" id="submit-button" type="submit">Search</button>
</form>
</div>
</nav>
<!--RESULTS-->
<div class="container-fluid">
<div class="container-results" id="container-results"> </div>
</div>
</body>
</html>
Vishal is correct. This is throwing an error because you are navigating away from the page when they submit.
Change your event listener to start like this and the problem goes away:
submitBtnEl.addEventListener("click", e => {
e.preventDefault();
When the user navigates away, the request is aborted, thus the error handler fires.
You can see this in action (before you fix it as above) by looking at the network tab. The request shows "cancelled", i.e. the browser cancelled the request.
It's a little confusing here, because the order of events is:
User clicks the submit button
The event listener you created runs
Inside of it, your fetch fires, including the establishment of its error handler
When your event listener finishes, the default event handler runs. Since this is a form, and the button was a 'submit' type, the default event handler is to submit the form. When no action URL is given, it presumes the handler is the same page.
The browser begins the process of navigating (i.e. submitting) to the same page.
The browser cancels the fetch request, since the user is navigating "away" from the current page.
The fetch request, having been cancelled, has now errored, and thus the error handler fires
Your alert runs inside the error handler, pausing the execution of the page, including the navigation
So at that point it seems like they haven't navigated yet, but the process has already started enough to have cancelled the request.
Im trying to write a Python code editor in browser using Skulpt to execute the Python code and Code Mirror as a text editor.
As the input function for Skulpt uses an alert for input, I have decided to write my own function. The input function I have written works and takes an input from a modal.
Sk.configure({output:outf, read:builtinRead, __future__: Sk.python3, inputfun: function (prompt) {
clearModal();
addModalQuestion(prompt);
toggleModal();
// the function returns a promise to give a result back later...
return new Promise(function(resolve,reject){
$("#modal-submit").on("click",function(e){
// resolve the promise with the value of the input field
resolve($("#modal-input").val());
})
})
}, inputfunTakesPrompt: true});
Any errors in the code are usually sent to the output pre:
For normal errors with no input I get this (which is what I want to happen):
However, when I use an input in my code no error message is output:
The errors will no longer be displayed and I receive the following error:
Does anyone have any idea how I could resolve this issue or point me in the right direction?
I've put both my skulpt.js and index.html file below if this helps.
SkulptTest.js
// output functions are configurable. This one just appends some text
// to a pre element.
function outf(text) {
var mypre = document.getElementById("output");
mypre.innerHTML = mypre.innerHTML + text;
}
function builtinRead(x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
throw "File not found: '" + x + "'";
return Sk.builtinFiles["files"][x];
}
// Here's everything you need to run a python program in skulpt
// grab the code from your textarea
// get a reference to your pre element for output
// configure the output function
// call Sk.importMainWithBody()
function runit() {
var prog = editor.getValue(); ;
var mypre = document.getElementById("output");
mypre.innerHTML = '';
Sk.pre = "output";
Sk.configure({output:outf, read:builtinRead, __future__: Sk.python3, inputfun: function (prompt) {
clearModal();
addModalQuestion(prompt);
toggleModal();
// the function returns a promise to give a result back later...
return new Promise(function(resolve,reject){
$("#modal-submit").on("click",function(e){
// resolve the promise with the value of the input field
resolve($("#modal-input").val());
})
})
}, inputfunTakesPrompt: true});
(Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target = 'mycanvas';
var myPromise = Sk.misceval.asyncToPromise(function() {
try {
if (result = Sk.importMainWithBody("<stdin>", false, prog, true)) {
return result;
}
}
catch(e) {
outf(e.toString());
}
});
;
}
index.html
<!DOCTYPE html>
<html>
<head>
<!--JQuery-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" type="text/javascript"></script>
<!--Skulpt-->
<script src="skulpt/skulpt.min.js" type="text/javascript"></script>
<script src="skulpt/skulpt-stdlib.js" type="text/javascript"></script>
<!--Code Mirror-->
<script src="codemirror/lib/codemirror.js"></script>
<link href="codemirror/lib/codemirror.css" rel="stylesheet">
<script src="codemirror/mode/python/python.js"></script>
<link href="codemirror/theme/midnight.css" rel="stylesheet">
<!--My Styles-->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Input</title>
<meta name="description" content="How do we input data in Python 3?">
<link href="css/reset.css" rel="stylesheet" type="text/css">
<style>
#editor-container {
width: 100vw;
height: 47vh;
}
#run-container {
width: 100vw;
height: 5vh;
background-color: #0a121f;
}
#run-container button {
float: right;
height: 5vh;
width: 15%;
background-color: yellow;
border: none;
border-radius: 5px;
}
#output-container {
width: calc(100vw - 10px);
height: calc(45vh - 10px);
background-color: aliceblue;
float: right;
background-color: #000;
color: #fff;
padding-left: 10px;
padding-top: 10px;
}
#output {
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
</style>
<!--Modal-->
<link href="css/modal.css" rel="stylesheet" type="text/css">
</head>
<body>
<!--Skulp-->
<script src="skulptTest.js"></script>
<!--My Code-->
<div id="right-panel">
<div id="editor-container">
<div class="modal" id="modal">
<div class="modal-content">
<span class="close-button"></span>
<p id="modal-question" class="modal-question">Input Prompt</p>
<input type="text" id="modal-input" name="modal-input" class="modal-input">
<button id="modal-submit" class="modal-submit" onclick="toggleModal()">Submit</button>
</div>
</div>
<textarea id="editor"></textarea>
</div>
<div id="run-container">
<button type="button" onclick="runit()">Run</button>
</div>
</div>
<div id="output-container">
<pre id="output"></pre>
</div>
<!-- Code Mirror-->
<script src="js/code-mirror.js"></script>
<script>editor.setValue("name = input('What is your name?')\nprint(name)");</script>
</body>
</html>
<script src="js/modal.js"></script>
I've also attached a link to all of the files below.
Code Editor Files
If anyone could help me with this I'd really appreciate it
Thanks in advance,
Sean
This question already has answers here:
Compare two last character in a string
(2 answers)
Closed 4 years ago.
I'm trying to create a simple add calculator. As of now I am successful on displaying the numbers and concatenating them. But I what I don't want is when I clicked the plus(add) button two or more times, it will also concatenate with another plus symbol. Is there a way for me that if ever I clicked the plus button twice. the second symbol will no longer display. Like if it detects that the previous input is a plus symbol. it will never concatenate with each other. Sorry if my English is not clear.
Sample Error when i clicked the add button multiple times: ( 111++++222 ) instead of just 111+222
Here's my code guys:
<!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>
<style>
body {
margin: 0px auto;
width: 600px;
}
p {
font-size: 23px;
float: left;
padding: 30px;
border: solid #336336 2px;
margin: 20px;
}
</style>
</head>
<body>
<h1 id="result">aaww </h1>
<p id="1" class="one">1</p>
<p id="2" class="two">2</p>
</br></br>
<p id="add">+</p>
</br></br>
<p id="equals">=</p>
<!-- <p class="cancel">cancel</p> <p class="cancel">cancel</p> -->
<p class="clear-tasks"> CLEAR</p>
<script>
//PLACE HOLDER FOR THE RESULT
let Result = document.getElementById("result");
Result.innerText = "RESULT HERE";
// CLEAR BUTTON
let clear = document.querySelector('.clear-tasks');
// EVENT LISTENER TO CLEAR THE BUTTON
clear.addEventListener('click', function(){
Result.textContent = '';
});
let addition = document.querySelector("#add");
addition.addEventListener('click',runEventAdd);
function runEventAdd(e){
Result.textContent += ' + ';
}
//ONE BUTTON
const numberOne = document.querySelector('.one');
// EVENT LISTENER TO CONCATINATE 1
numberOne.addEventListener('click', runEvent);
function runEvent(e) {
if (Result.textContent === 'RESULT HERE') {
Result.textContent = 1;
} else {Result.textContent += 1;
}
}
//TWO BUTTON
const numberTwo = document.querySelector('.two');
// EVENT LISTENER TO CONCATINATE 2
numberTwo.addEventListener('click', runEvent2);
function runEvent2(e) {
if (Result.textContent === 'RESULT HERE') {
Result.textContent = 2;
} else {Result.textContent += 2;
}
}
</script>
</body>
</html>
Just use endsWith to check if the current string ends with a +:
addition.addEventListener('click',runEventAdd);
function runEventAdd(e){
if (!Result.textContent.endsWith(' + '))
Result.textContent += ' + ';
}
Use an if statement to check if there is already an operator. I made something similar in Java with GUI instead of JS but thats what I did and it worked fine. If you do the if statement you could use if(str.indexOf(operator) == -1) {
do the concatenation.
Check the last value of your result. If it is a '+', don't add another '+'
//PLACE HOLDER FOR THE RESULT
let Result = document.getElementById("result");
Result.innerText = "RESULT HERE";
// CLEAR BUTTON
let clear = document.querySelector('.clear-tasks');
// EVENT LISTENER TO CLEAR THE BUTTON
clear.addEventListener('click', function(){
Result.textContent = '';
});
let addition = document.querySelector("#add");
addition.addEventListener('click',runEventAdd);
function runEventAdd(e){
if(Result.innerText.slice(-1) != '+')
{
Result.textContent += ' + ';
}
}
//ONE BUTTON
const numberOne = document.querySelector('.one');
// EVENT LISTENER TO CONCATINATE 1
numberOne.addEventListener('click', runEvent);
function runEvent(e) {
if (Result.textContent === 'RESULT HERE') {
Result.textContent = 1;
} else {Result.textContent += 1;
}
}
//TWO BUTTON
const numberTwo = document.querySelector('.two');
// EVENT LISTENER TO CONCATINATE 2
numberTwo.addEventListener('click', runEvent2);
function runEvent2(e) {
if (Result.textContent === 'RESULT HERE') {
Result.textContent = 2;
} else {Result.textContent += 2;
}
}
<!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>
<style>
body {
margin: 0px auto;
width: 600px;
}
p {
font-size: 23px;
float: left;
padding: 30px;
border: solid #336336 2px;
margin: 20px;
}
</style>
</head>
<body>
<h1 id="result">aaww </h1>
<p id="1" class="one">1</p>
<p id="2" class="two">2</p>
</br></br>
<p id="add">+</p>
</br></br>
<p id="equals">=</p>
<!-- <p class="cancel">cancel</p> <p class="cancel">cancel</p> -->
<p class="clear-tasks"> CLEAR</p>
</body>
</html>
The Goal:
A button which displays an alert with "Hello world!" and some radio buttons which display a warning when the third one is selected.
The HTML:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>hello world</title>
<link rel="stylesheet" href="style.css">
<meta name="description" content="">
</head>
<body>
<div id="main">
<p>text</p>
link
<button>button</button>
<form>
<fieldset>
<legend>Legend</legend>
<label for="radio1">Option 1</label>
<input type="radio" name="radio-buttons" value="option-1" id="radio1"/>
<label for="radio2">Option 2</label>
<input type="radio" name="radio-buttons" value="option-2" id="radio2"/>
<label for="radio3">Option 3</label>
<input type="radio" name="radio-buttons" value="option-3" id="radio3"/>
<p id="warn">No, pick another one.</p>
</fieldset>
</form>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
The CSS:
Most of this really doesn't matter. The important thing is #warn which is supposed to only show when the third option is selected.
a,
button {
display: block;
margin-bottom: 1em;
}
fieldset {
width: 245px;
height: 75px;
background: #dfe;
position: relative;
}
legend {
background: white;
}
#warn {
display: none;
background: #d33;
color: #fff;
font-family: helvetica;
padding: 10px 15px 10px;
margin: 0 -12px;
position: absolute;
top: 52px;
width: 239px;
}
The JavaScript:
I think the problem is in my event handlers, but I don't know for sure. BTW yes I know there's some extraneous stuff here; like I said I'm just screwing around.
// variables
var p = document.getElementsByTagName("p");
var a = document.getElementsByTagName("a");
var button = document.getElementsByTagName("button");
var fieldset = document.getElementsByTagName("fieldset");
var radio1 = document.getElementById("radio1");
var radio2 = document.getElementById("radio2");
var radio3 = document.getElementById("radio3");
var warn = document.getElementById("warn");
// functions
function prepareEventHandlers() {
button.onclick = function() {
alert("Hello world!")
};
radio3.onfocus = function() {
warn.setAttribute("display","inherit")
}
}
// window onload
window.onload = function() {
prepareEventHandlers();
}
Notice the name of the function:
document.getElementsByTagName()
// ^ That's an "s", so the function
// returns an array of elements.
button.onclick won't work because button is an array of buttons (I would name it buttons), so you have to iterate:
for (var i = 0; i < button.length; i++) {
button[i].onclick = ...
}
Since you have only one button, I would just give it an id and use document.getElementById() to fetch the single button and attach the onclick handler.
First, go fo button like this,
var button = document.getElementsByTagName("button")[0];
getElementsByTagName returns the array of matched elements...
For radio button
Try this
display is a CSS property. Using display as an HTML attribute will not hide or show content. You have to access CSS properties using style attribute. like,
radio3.onclick = function() {
warn.style.display = "inherit";
}