I have a problem. I was wrote a simple chat Spring boot Application and a frontend to it. But I need to use port 9090, because the 8080 is already in use.
This is My configuration Java file
And a FrontEnd code, where I connect to the server.
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat</title>
<style>
#chat-window {
width: 500px;
height: 400px;
border: 1px solid black;
overflow-y: scroll;
}
.message-container {
display: flex;
justify-content: space-between;
margin: 10px;
}
.username {
font-weight: bold;
margin-right: 10px;
}
</style>
</head>
<body>
<h1>WebSocket Chat</h1>
<div id="chat-window"></div>
<form>
<input type="text" id="username" placeholder="Enter your username">
<input type="text" id="message" placeholder="Enter your message">
<button type="submit">Send</button>
</form>
<script src="https://cdn.jsdelivr.net/npm/sockjs-client#1.5.0/dist/sockjs.min.js"></script>
<script>
const chatWindow = document.querySelector("#chat-window");
const usernameInput = document.querySelector("#username");
const messageInput = document.querySelector("#message");
const form = document.querySelector("form");
const socket = new WebSocket("ws://localhost:9090/chat");
form.addEventListener("submit", event => {
event.preventDefault();
const message = {
username: usernameInput.value,
content: messageInput.value
};
socket.send(JSON.stringify(message));
messageInput.value = "";
});
socket.addEventListener("message", event => {
const message = JSON.parse(event.data);
const messageElement = document.createElement("div");
messageElement.classList.add("message-container");
messageElement.innerHTML = `
<div class="username">${message.username}:</div>
<div>${message.content}</div>
`;
chatWindow.appendChild(messageElement);
});
</script>
</body>
</html>
I have an application.properties file, where server.port=9090
Pls help me to solve this problem, I have already past setClientlibraryUrl("http://localhost:9090/sockjs-client.min.js"), but this all not work
Related
When I type in something in the text area element and then click on the read button nothing is being uttered. The console doesn't throw any error and I can't identify where I've gone wrong either. I went on the "SpeechUtterance" MDN documentation and as far as I can tell I've followed all the right steps. Help please!
const read = document.getElementById("read");
const pause = document.getElementById("pause");
const stop = document.getElementById("stop");
const speed = document.getElementById("speed");
const text = document.getElementById("text");
read.addEventListener("click", () => {
readText(text.value)
});
pause.addEventListener("click", () => {
pauseText();
});
function readText(dummy) {
var utterThis = new SpeechSynthesisUtterance(dummy);
if(speechSynthesis.speaking && speechSynthesis.paused) {
return speechSynthesis.resume()
}
if(speechSynthesis.speaking) return;
console.log(utterThis)
console.log(speechSynthesis)
utterThis.text = dummy;
utterThis.rate = speed.value
text.disabled = true;
speechSynthesis.speak(utterThis)
utterThis.addEventListener("end", () => {
text.disabled = false
})
}
function pauseText() {
if(speechSynthesis.speaking) speechSynthesis.pause();
}
body {
background-color: purple;
}
textarea {
margin-top: 50px;
margin: auto;
}
textarea:focus {
background: green;
}
.container {
display: flex;
justify-content: center;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
<title></title>
</head>
<body>
<textarea id="text" name="name" rows="30" cols="100"></textarea>
<div class="container">
<label for="speed">Speed</label>
<input id="speed" type="number" min="0" step="1" max="10">
<button id="read" type="button" name="button">Read</button>
<button id="pause" type="button" name="button">Pause</button>
<button id="stop" type="button" name="button">Stop</button>
</div>
</body>
<script src="index.js" charset="utf-8"></script>
</html>
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>
I'm trying to get the two players to take turns in my tic-tac-toe project. In my playerContols function I've tried to put each player in a "current PLayer" housing variable that will switch out depending if one player went already but it just gets stuck on player 2 and just mark every cell with O's. I'm not entirely sure what's wrong with it
my code
const playgame = (() => {
const playerOne = {
Name: 'playerOne',
Marking: 'X'
};
const playerTwo = {
Name: 'PlayerTwo',
Marking: 'O'
};
function playerControls(e) {
let currentPlayer;
currentPlayer = playerOne;
e.target.textContent = currentPlayer.Marking;
if (currentPlayer === playerOne) {
currentPlayer = playerTwo;
e.target.textContent = currentPlayer.Marking;
} else {
currentPlayer = playerOne;
e.target.textContent = currentPlayer.Marking;
}
}
return {
playerControls
}
})();
const gameBoard = (() => {
const makeBoard = (rows, cols) => {
const theBoard = document.getElementById("GameBoard");
theBoard.style.gridTemplateColumns = `repeat(${cols}, 1fr)`;
theBoard.style.gridTemplateRows = `repeat(${rows}, 1fr)`;
for (i = 0; i < (rows * cols); i++) {
let gameDivs = document.createElement("div");
gameDivs.addEventListener("click", playgame.playerControls)
theBoard.appendChild(gameDivs).classList.add("newdivgrid");
}
};
makeBoard(3, 3);
})();
#GameBoard {
width: 600px;
height: 350px;
border: 1px solid darkblue;
margin-left: 27%;
text-align: center;
font-size: 500%;
font-family: cursive, sans-serif;
display: grid;
}
.newdivgrid {
border: 1px solid black;
grid-row-gap: 50px;
}
.newdivgrid:hover {
background-color: aqua;
}
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tic-Tac-Toe game</title>
<link rel="stylesheet" href="Tic-Tac-Toe.css">
</head>
<h1>Tic-Tac-Toe Project</h1>
<div id="PlayerSelectionContainer">
<h2>Select Players</h2>
<div class="Player1">
<h3>Player 1</h3>
<div class="playerSelectionButtons" data-player="playerOne">
<button data-player="human">Human</button>
<button data-player="computer">Computer</button>
</div>
</div>
<div class="Player2">
<h3>Player 2</h3>
<div class="playerSelectionButtons" data-player="playerTwo">
<button data-human-player="human">Human</button>
<button data-computer-player="computer">Computer</button>
</div>
</div>
</div>
<div id="GameBoard">
</div>
<div id="resultContainer">
<h3>Results</h3>
<div class="player1Results">
<h3>Player 1 Results</h3>
<textarea placeholder="0" disabled></textarea>
</div>
<div class="Player2Results">
<h3>Player 2 Results</h3>
<textarea placeholder="0" disabled></textarea>
</div>
</div>
<body>
<script src="Tic-Tac-Toe.js"></script>
</body>
</html>
The issue is that your currentPlayer variable declaration and initialization needs to live outside the playerControls function or else you're just resetting it to playerOne each time.
let currentPlayer;
currentPlayer = playerOne;
function playerControls(e){...}
Here is the fix in action:
const playgame = (()=> {
const playerOne = {
Name: 'playerOne',
Marking: 'X'
};
const playerTwo = {
Name: 'PlayerTwo',
Marking: 'O'
};
let currentPlayer;
currentPlayer = playerOne;
function playerControls(e){
e.target.textContent = currentPlayer.Marking;
if(currentPlayer === playerOne)
{
currentPlayer = playerTwo;
e.target.textContent = currentPlayer.Marking;
}else{
currentPlayer = playerOne;
e.target.textContent = currentPlayer.Marking;
}
}
return{playerControls}
})();
const gameBoard = (() => {
const makeBoard = (rows, cols) => {
const theBoard = document.getElementById("GameBoard");
theBoard.style.gridTemplateColumns = `repeat(${cols}, 1fr)`;
theBoard.style.gridTemplateRows = `repeat(${rows}, 1fr)`;
for (i=0; i<(rows * cols); i++){
let gameDivs = document.createElement("div");
gameDivs.addEventListener("click", playgame.playerControls)
theBoard.appendChild(gameDivs).classList.add("newdivgrid");
}
};
makeBoard(3,3);
})();
#GameBoard{
width: 600px;
height: 350px;
border: 1px solid darkblue;
margin-left: 27%;
text-align: center;
font-size: 500%;
font-family: cursive, sans-serif;
display: grid;
}
.newdivgrid{
border: 1px solid black;
grid-row-gap: 50px;
}
.newdivgrid:hover{
background-color: aqua;
}
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tic-Tac-Toe game</title>
<link rel="stylesheet" href="Tic-Tac-Toe.css">
</head>
<h1>Tic-Tac-Toe Project</h1>
<div id="PlayerSelectionContainer">
<h2>Select Players</h2>
<div class="Player1">
<h3>Player 1</h3>
<div class="playerSelectionButtons" data-player="playerOne">
<button data-player="human">Human</button>
<button data-player="computer">Computer</button>
</div>
</div>
<div class="Player2">
<h3>Player 2</h3>
<div class="playerSelectionButtons" data-player="playerTwo">
<button data-human-player="human">Human</button>
<button data-computer-player="computer">Computer</button>
</div>
</div>
</div>
<div id="GameBoard">
</div>
<div id="resultContainer">
<h3>Results</h3>
<div class="player1Results">
<h3>Player 1 Results</h3>
<textarea placeholder="0" disabled ></textarea>
</div>
<div class="Player2Results">
<h3>Player 2 Results</h3>
<textarea placeholder="0" disabled ></textarea>
</div>
</div>
<body>
<script src="Tic-Tac-Toe.js"></script>
</body>
</html>
I have a html form and would like to use an eventlistener every click on submit button and insert the textarea and textinput to an alert.
the fuction of event.target.value is not working for me and the userinput is not set to a variable.
why eventa.target.value is not working? and how can I use the userinput?
Code:
var myinput = document.getElementById('myinput');
var mytext = document.getElementById('mytext').target.value;
var myform = document.getElementById('myform');
myform.addEventListener("change", function(event) {
alert(mytext);
})
myform.addEventListener("click", function(event) {
alert(mytext);
})
input[type="text"] {
width: 200px;
height: 20px;
}
input[type="submit"] {
width: 100px;
height: 50px;
}
<form action="" id="myform">
<input type="text" id="myinput" />
<br/>
<textarea id="mytext" cols="30" rows="10"></textarea>
<input type="submit" id='submit' />
</form>
You can use the below snippet and keep in mind that target of the event is what you put the click event on. so the target will be the submit button which you don't want. also target.value only works on the target not in any other element in the DOM
const myinput = document.getElementById('myinput');
const mytext = document.getElementById('mytext');
const submitButton = document.getElementById('submit');
submitButton.addEventListener("click", function(event){
const textInput = myinput.value;
const textArea = mytext.value;
alert(`the text Input: '${textInput}' and the text Area: '${textArea}'`);
});
<!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>
input[type="text"] {
width: 200px;
height: 20px;
}
input[type="submit"] {
width: 100px;
height: 50px;
}
</style>
</head>
<body>
<form action="" id="myform">
<input type="text" id="myinput"/>
<br/>
<textarea id="mytext" cols="30" rows="10"></textarea>
<input type="submit" id='submit' />
</form>
</body>
<script src="script.js"></script>
</html>
why eventa.target.value is not working?
Because you are not using Event.target.value. You are trying to use HTMLElement.target.value which of course is undefined because HTMLElement does not have a target property. However, in the case of HTMLInputElement and HTMLTextareaElement they do have a value property which you can read in your event listener:
var myinput = document.getElementById('myinput');
var mytext = document.getElementById('mytext');
var myform = document.getElementById('myform');
myform.addEventListener("change", function(event) {
console.log(mytext.value);
console.log(myinput.value);
})
myform.addEventListener("submit", function(event) {
event.preventDefault();
console.log(mytext.value);
console.log(myinput.value);
})
input[type="text"] {
width: 200px;
height: 20px;
}
input[type="submit"] {
width: 100px;
height: 50px;
}
<form action="" id="myform">
<input type="text" id="myinput" />
<br/>
<textarea id="mytext" cols="30" rows="10"></textarea>
<input type="submit" id='submit' />
</form>
Please note that the change event might only occur as soon as you the input element emits a blur event (depending on the browser you're using).
I'm trying to make a list that allows a user to submit issues. Im using knockout and i can get it to do exactly what i wanted it to do but when i try to debug in microsoft visual studios it does not work they way I want it to. When I debug, the page opens the same as in the fiddle except the "test issue" is missing from the issue list. Also you can type in the add issue text box but when you hit submit it clears and does not add to the issue list
I was told I needed to add an onready, but im still new to learning how to code and am unsure of
A.How to do it
B. Where to put it
Here is my fiddle
http://jsfiddle.net/grahamwalsh/rCB9V/
and here is my code
IssueList ( html )
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Issue List</title>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/knockout-3.1.0.js"></script>
<script src="Issuelist.js"></script>
<link type="text/css" rel="stylesheet" href="Issuelistcss.css" />
</head>
<body>
<div class='issuelist'>
<form data-bind="submit:addIssue">
Add Issue: <input type="text" data-bind='value:issueToAdd, valueUpdate: "afterkeydown"' />
<button type="submit" data-bind="enable: issueToAdd().length > 0">Add</button>
</form>
<p>Your Issues:</p>
<select multiple="multiple" height="5" data-bind="options:allIssues, selectedOptions:selectedIssues"> </select>
<div>
<button data-bind="click: removeSelected, enable: selectedIssues().length > 0">Remove</button>
<button data-bind="click: sortIssues, enable: allIssues().length > 1">Sort</button>
</div>
</div>
</body>
</html>
Css
body { font-family: arial; font-size: 14px; }
.issuelist { padding: 1em; background-color: #87CEEB; border: 1px solid #CCC; max-width: 655px; }
.issuelist input { font-family: Arial; }
.issuelist b { font-weight: bold; }
.issuelist p { margin-top: 0.9em; margin-bottom: 0.9em; }
.issuelist select[multiple] { width: 100%; height: 8em; }
.issuelist h2 { margin-top: 0.4em; }
js
var Issuelist = function () {
this.issueToAdd = ko.observable("");
this.allIssues = ko.observableArray(["test"]);
this.selectedIssues = ko.observableArray(["test"]);
this.addIssue = function () {
if ((this.issueToAdd() != "") && (this.allIssues.indexOf(this.issueToAdd()) < 0))
this.allIssues.push(this.issueToAdd());
this.issueToAdd("");
};
this.removeSelected = function () {
this.allIssues.removeAll(this.selectedIssues());
this.selectedIssues([]);
};
this.sortIssues = function () {
this.allIssues.sort();
};
};
ko.applyBindings(new Issuelist());
To run a function when the page is ready using jQuery:
$(document).ready(function(){
//Code goes here
}