I want to create a chat system (which i already accomplished), but a working username selector, and it gets the username in the input, then when the user sends a message via chat, it is their username!! And also, i tried putting it in a localStorage, so when the user refreshes or rejoins, the name is still there and not removed! I think im close, but it says UNDEFINED, which really got me confused? Please help? Thanks!!
localStorage.playerusername = document.querySelector(".hud-name").value;
let username = localStorage.playerusername;
let chatMsg = [];
function appendChatMessage(currentUserName, chatMessage) {
let chatElem = document.createElement("p");
chatElem.innerHTML = "<strong>" + currentUserName + ": </strong>" + chatMessage;
document.querySelector(".chat").appendChild(chatElem);
}
for (let i = 0; i < chatMsg.length; i++) {
appendChatMessage(username, chatMsg[i])
}
let Game = {
currentGame: {
variables: {
sendMessage: function(messageContent) {
chatMsg.push(messageContent);
appendChatMessage(username, messageContent);
document.querySelector(".enterT").innerHTML = ""
},
addChatTopRemoverPackage: async function() {
if (chatMsg.length == 7) {
let chatElem = document.querySelector(".chat")
if (chatElem.children[0]) {
chatElem.removeChild(chatElem.children[0])
if (chatMsg.length > 0) {
chatMsg.shift()
//if (chatMsg.length == 0) {
//chatMsg.pop();
//}
}
}
}
},
chatRemoverRefresher: setInterval(() => {
Game.currentGame.variables.addChatTopRemoverPackage()
}, 0.000000000001)
}
}
}
HTML:
<div class="hud-name-select
type-text
maxlength-16
">
<input class="hud-name" type="text" maxlength="16" placeholder="Enter Nickname...">
<div></div>
<div><br></div>
<button class="btn-play btn-green background-color-green">
<div style="
display: none;
" display="none">Loading......<div></div>
</div>
<span>Play</span>
</button>
</div>
</div>
</div>
<div class="msgcont">
<div class="messages">
<h1>
CHAT
</h1>
<div class="chat">
</div>
<div>
<input class="enterT" type="text" placeholder="Enter A Message..!"><button
onclick="Game.currentGame.variables.sendMessage(document.querySelector('.enterT').value)">send
message</button>
</div>
<br>
</div>
</div>
Kevin
Related
I'm beginner in javascript, so please bear with me.
I've a form in which i validate the controls with javascript. the error is displayed on clicking submit button when the fields are empty or where validation are not valid.
What I would like to do is to remove error message if i type in the right info in the field without clicking submit button.
const paragraph = document.querySelector('p');
const form = document.getElementById('create-account-form');
const usernameInput = document.getElementById('username');
form.addEventListener('submit', (event) => {
// btn.setAttribute('disabled', 'disabled');
validateForm();
console.log(isFormValid());
if (isFormValid() == true) {
form.submit();
} else {
event.preventDefault();
}
});
function isFormValid() {
const inputContainers = form.querySelectorAll('.input-group');
let result = true;
inputContainers.forEach((container) => {
if (container.classList.contains('error')) {
result = false;
}
});
return result;
}
function validateForm() {
//USERNAME
if (usernameInput.value.trim() == '') {
setError(usernameInput, 'Name can not be empty');
} else if (usernameInput.value.trim().length < 5 || usernameInput.value.trim().length > 15) {
setError(usernameInput, 'Name must be min 5 and max 15 charecters');
usernameInput.focus();
} else {
document.querySelector('p').textContent = "";
setSuccess(usernameInput);
}
}
function setError(element, errorMessage) {
const parent = element.parentElement;
if (parent.classList.contains('success')) {
parent.classList.remove('success');
}
parent.classList.add('error');
paragraph.textContent = errorMessage;
}
function setSuccess(element) {
const parent = element.parentElement;
if (parent.classList.contains('error')) {
parent.classList.remove('error');
}
parent.classList.add('success');
}
<form id="create-account-form" action="result.html" method="GET">
<div class="title">
<h2>Create Account</h2>
</div>
<!-- USERNAME -->
<div class="input-group">
<label for="username">Name</label>
<input type="text" id="username" placeholder="Name" name="username">
<p>Error Message</p>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
You can use the input listener to do this.
See the codes below. I've done certain changes in the code.
modified your <input> as below.
<input type="text" id="username" placeholder="Name" name="username" oninput="validateForm(this)">
Read more about it in the docs
const paragraph = document.querySelector('p');
function isFormValid() {
const inputContainers = form.querySelectorAll('.input-group');
let result = true;
inputContainers.forEach((container) => {
if (container.classList.contains('error')) {
result = false;
}
});
return result;
}
function validateForm(usernameInput) {
//USERNAME
if (usernameInput.value.trim() == '') {
setError(usernameInput, 'Name can not be empty');
} else if (usernameInput.value.trim().length < 5 || usernameInput.value.trim().length > 15) {
setError(usernameInput, 'Name must be min 5 and max 15 charecters');
usernameInput.focus();
} else {
document.getElementById('error_p').textContent = "";
setSuccess(usernameInput);
}
}
function setError(element, errorMessage) {
const parent = element.parentElement;
if (parent.classList.contains('success')) {
parent.classList.remove('success');
}
parent.classList.add('error');
paragraph.textContent = errorMessage;
}
function setSuccess(element) {
const parent = element.parentElement;
if (parent.classList.contains('error')) {
parent.classList.remove('error');
}
parent.classList.add('success');
}
<form id="create-account-form" action="result.html" method="GET">
<div class="title">
<h2>Create Account</h2>
</div>
<!-- USERNAME -->
<div class="input-group">
<label for="username">Name</label>
<input type="text" id="username" placeholder="Name" name="username" oninput="validateForm(this)">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<p id="error_p">Error Message</p>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
I don't know javascript but I want to use, search on my site. I found a good example on stackoverflow link
I joined all the parts and received the following code:
function SearchName() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('target');
var card = document.getElementsByClassName('card');
for (i = 0; i < nodes.length; i++) {
if (nodes[i].innerText.toLowerCase().includes(filter)) {
card[i].style.display = "block";
} else {
card[i].style.display = "none";
}
}
}
<input id="Search" onkeyup="SearchName();" class="form-control dsh191" type="text" placeholder="search" name="" />
<div class="d-flex m-0 p-0">
<div class="card">
Abc Def
<p class="dsh185">Code: <span class="code">1234</span></p>
</div>
<div class="card">
Qwr Tyu
<p class="dsh185">Code: <span class="code">5678</span></p>
</div>
<div class="card">
Iop Klj
<p class="dsh185">Code: <span class="code">9000</span></p>
</div>
</div>
Everything works fine, but I need to search by class = 'code'. My question is:
How do I search for Qwr Tyu and <p class="dsh185">Code: <span class="code">5678</span></p> ? What did I try?
I duplicated javascript function code and changed the class from target to code, but nothing was received, now the search goes after the first function in the input.
I added a new function to the input SearchCode();;
In <span>5678</span> I added class="code"
And as I said above I dubbed javascript code and I changed 2 variables: from nodes to code new class name and from card to profilecard, only the new variable but the html tag remains the same.
function SearchName() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('target');
var card = document.getElementsByClassName('card');
for (i = 0; i < nodes.length; i++) {
if (nodes[i].innerText.toLowerCase().includes(filter)) {
card[i].style.display = "block";
} else {
card[i].style.display = "none";
}
}
}
function SearchCode() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var code = document.getElementsByClassName('code');
var profilecard = document.getElementsByClassName('card');
for (i = 0; i < code.length; i++) {
if (code[i].innerText.toLowerCase().includes(filter)) {
profilecard[i].style.display = "block";
} else {
profilecard[i].style.display = "none";
}
}
}
<input id="Search" onkeyup="SearchName(); SearchCode();" class="form-control dsh191" type="text" placeholder="search" name="" />
<div class="d-flex m-0 p-0">
<div class="card">
Abc Def
<p class="dsh185">Code: <span class="code">1234</span></p>
</div>
<div class="card">
Qwr Tyu
<p class="dsh185">Code: <span class="code">5678</span></p>
</div>
<div class="card">
Iop Klj
<p class="dsh185">Code: <span class="code">9000</span></p>
</div>
</div>
My question: How can I search the site after 2 html tags (Search by text in tags)?
Any idea how I can change the code, or where I went wrong etc ... Thanks
one idea can be to use innerText on parent tag profileCard
function SearchName() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('target');
var card = document.getElementsByClassName('card');
for (i = 0; i < nodes.length; i++) {
if (nodes[i].innerText.toLowerCase().includes(filter)) {
card[i].style.display = "block";
} else {
card[i].style.display = "none";
}
}
}
function SearchCode() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var code = document.getElementsByClassName('code');
var profilecard = document.getElementsByClassName('card');
for (i = 0; i < code.length; i++) {
if (profilecard[i].innerText.toLowerCase().includes(filter)) {
profilecard[i].style.display = 'block';
} else {
profilecard[i].style.display = 'none';
}
}
}
<input id="Search" onkeyup="SearchName(); SearchCode();" class="form-control dsh191" type="text" placeholder="search" name="" />
<div class="d-flex m-0 p-0">
<div class="card">
Abc Def
<p class="dsh185">Code: <span class="code">1234</span></p>
</div>
<div class="card">
Qwr Tyu
<p class="dsh185">Code: <span class="code">5678</span></p>
</div>
<div class="card">
Iop Klj
<p class="dsh185">Code: <span class="code">9000</span></p>
</div>
</div>
I have this code in html and javascript
HTML
function getResult() {
let answer_one = document.getElementById("question_one").value;
let correct_ans = 0;
let result = "You answered " + correct_ans + " correctly.";
if (answer_one === "abuja") {
correct_ans++;
}
document.getElementById("result").innerHTML = result;
}
<div class="container">
<div class="question1">
<p>What is the capital of Nigeria</p><br>
<input type="text" id="question_one">
</div>
<button id="button" onclick="getResult();">Submit</button>
</div>
<!--end of container-->
<div class="button_after">
<h1 id="result"></h1>
</div>
<!--end of button_after-->
my issue is that the correct_ans variable doesn't add when i type in the correct answer in the textbox
You should initialize the variable result after you check for the correct answer.
function getResult() {
let correct_ans = 0;
let answer_one = document.getElementById("question_one").value;
if (answer_one === "abuja") correct_ans++;
let result = "You answered " + correct_ans + " correctly.";
document.getElementById("result").innerHTML = result;
}
<div class="container">
<div class="question1">
<p>What is the capital of Nigeria</p><br>
<input type="text" id="question_one">
</div>
<button id="button" onclick="getResult();">Submit</button>
</div>
<!--end of container-->
<div class="button_after">
<h1 id="result"></h1>
</div>
<!--end of button_after-->
In your code, result was evaluated before the correct_ans increment.
Try this instead.
function getResult() {
let answer_one = document.getElementById("question_one").value;
let correct_ans = 0;
let result = "";
if (answer_one === "abuja") {
correct_ans++;
}
result = You answered " + correct_ans + " correctly.
document.getElementById("result").innerHTML = result;
}
You declared the variable abuja before you updated the variable correct_ans. Put it after the if condition. If you'll add other questions you need to put the initial declaration of correct_ans = 0 out of the function or you're always going to get 0 or 1.
function getResult() {
let answer_one = document.getElementById("question_one").value;
let correct_ans = 0;
if (answer_one === "abuja") {
correct_ans++;
}
let result = "You answered " + correct_ans + " correctly.";
document.getElementById("result").innerHTML = result;
}
<div class="container">
<div class="question1">
<p>What is the capital of Nigeria</p><br>
<input type="text" id="question_one">
</div>
<button id="button" onclick="getResult();">Submit</button>
</div>
<!--end of container-->
<div class="button_after">
<h1 id="result"></h1>
</div>
<!--end of button_after-->
I am working on implementing a web chat and have come up with an issue that I hope is easily solvable.
How do I change the color for the sender/receiver to differenciate them?
I have tried to saving the colors into my db but the issue is how I can identify that I am the sender and the receivers color needs to be different.
This is how I have implemented my chat:
Chat.js
connection.on("SessionNotification", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var p = document.createElement("span");
var q = document.createElement("li");
p.setAttribute("class", "Sender");
q.setAttribute("class", "Message");
p.textContent = user + " - " + moment(datetime).format("DD-MM-YYYY HH:mm:ss");
q.textContent = msg;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
});
Html
<script>
$(document).ready(function () {
$('#MessageList').stop().animate({
scrollTop: $('#MessageList')[0].scrollHeight
}, 2000);
var SessionId = document.getElementById("Id").value;
console.log(SessionId);
var form_data = {
"SessionId": SessionId
};
$.ajax({
url: "#Url.Action("GetHistory", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/json",
success: function (result) {
console.log(result);
var output = JSON.parse(result);
for (var i = 0; i < output.length; i++) {
var p = document.createElement("span");
var q = document.createElement("li");
p.setAttribute("class", "Sender");
q.setAttribute("class", "Message");
p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
q.textContent = output[i].Message;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
}
},
error: function (error) {
console.log(error);
}
});
return false;
});
</script>
<div class="col-sm-12">
<h2>Session</h2>
<hr />
</div>
<div class="col-sm-12">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<div id="MessageListContainer">
<ul id="MessageList">
</ul>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
#Html.HiddenFor(m => m.Id)
#Html.HiddenFor(m => m.CurrentUser)
<input class="form-control col-sm-12" id="Message" type="text" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<div class="clearfix">
<div class="pull-right">
<input id="Send" type="button" value="Send" class="btn btn-primary" />
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-12">
<hr />
</div>
</div>
<script src="~/aspnet/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>
Your AJAX call that comes back as JSON appears to have a few fields like Name and CreatedOn. You can add an additional field server side for the SessionId, which you are injecting server-side anyway into your HTML. Then you can compare to see if the message's session matches yours. If so, then it is you and not the receiver. So you might have something like:
JS
// You set this earlier on
var SessionId = document.getElementById("Id").value;
// ........ OTHER CODE IN BETWEEN
for (var i = 0; i < output.length; i++) {
var p = document.createElement("span");
var q = document.createElement("li");
// If session ID matches current session (i.e. you) then add different class
if (output[i].SessionId === SessionId) {
// It is you
p.setAttribute("class", "Sender");
} else {
// It is other person
p.setAttribute("class", "Receiver");
}
q.setAttribute("class", "Message");
p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
q.textContent = output[i].Message;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
}
CSS
.Sender {
color: blue;
}
.Receiver {
color: green;
}
I am working on trying to link pages together so if a person were to login using the login page, they would be redirected to a specific created page, and if a user clicked the register button, they would be redirected to the register page and from there, after inputting in information, they would be directed to another page. The button for login or register does not work. Is there a way to fix this?
So far I have this for my login page.
function login() {
var users = ["admin1", "admin2", "admin3", "admin4"];
var pass = ["pass1", "pass2", "pass3", "pass4"];
ivar aUser = document.getElementById("user_name").value;
var aPass = document.getElementById("password").value;
for (i = 0; i < users.length; i++) {
if (users[i] == aUser && pass[i] == aPass) {
window.location = "dashboard.php";
break;
}
}
var myOut = document.getElementById("output");
myOut.innerHTML = "Who Are You? / Incorrect Password";
myOut.className = "error";
function init() {
var login_button = document.getElementById("login_button");
if (login_button !== null) {
login_button.onclick = login;
}
var register_button = document.getElementById("register_button");
if (register_button !== null) {
register_button.onclick = validation;
}
for (i = 1; i <= 10; i++) {
var myErr = document.getElementById("err" + i);
if (myErr !== null) {
myErr.className = "error";
}
}
}
<h1>
Please Login
</h1>
<form id="order_form">
<fieldset>
<legend>Login</legend>
<div class="tab">
<div class="tRow">
<div class="tRow">
<div class="tCell">
<label for="user_name">User Name:</label>
</div>
<div class="tCell">
<input type="text" id="user_name" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow> <div class=">
<label for="password">Password:</label>
</div>
<div class="tCell">
<input type="text" id="password" required="" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="login_button" value="Login" />
</div>
</div>
<!--END OF THIS SELECTION-->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="register_button" value="Register Now!" />
</div>
</div>
<!--END OF THIS SELECTION-->
</div>
<!-- END OF THE TABLE -->
<br />
<div id="output" class="error"></div>
</fieldset>
</form>
Validation function:
function validation() {
for (i=1; i<=10; i++) {
var myErr = document.getElementById("err" + i);
myErr.innerHTML = "";
}
document.getElementById("output").innerHTML = "";
var dept_name = document.getElementById("dept_name").value;
var user_email = document.getElementById("user_email").value;
var user_password = document.getElementById("user_password").value;
var phone_number = document.getElementById("phone_number").value;
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var office_location = document.getElementById("office_location").value;
var valid = true;
if (dept_name == "") {
document.getElementById("err1").innerHTML = "Invalid!";
valid = false;
}
if ((user_email) =="") {
valid = false;
document.getElementById("err2").innerHTML = "Invalid!";
}
if ((user_password) =="") {
valid = false;
document.getElementById("err3").innerHTML = "Invalid!";
}
if ((first_name) =="") {
valid = false;
document.getElementById("err4").innerHTML = "Invalid!";
}
if ((last_name) =="") {
valid = false;
document.getElementById("err5").innerHTML = "Invalid!";
}
if (isNaN(phone_number) || card_number.length !==11) {
valid = false;
document.getElementById("err6").innerHTML = "Invalid!";
}
if ((office_location) =="") {
valid = false;
document.getElementById("err7").innerHTML = "Invalid!";
}
}
window.onload=init;
Several errors
missing brackets
no execution of init
missing validation function
This works:
function login() {
var myOut = document.getElementById("output");
var users = ["admin1", "admin2", "admin3", "admin4"];
var pass = ["pass1", "pass2", "pass3", "pass4"];
var aUser = document.getElementById("user_name").value;
var aPass = document.getElementById("password").value;
for (i = 0; i < users.length; i++) {
if (users[i] == aUser && pass[i] == aPass) {
myOut.innerHTML = "Correct - you will be redirected";
setTimeout(function() {
window.location = "dashboard.php";
},1000);
return;
}
}
myOut.innerHTML = "Who Are You? / Incorrect Password";
myOut.className = "error";
}
function init() {
var login_button = document.getElementById("login_button");
if (login_button !== null) {
login_button.onclick = login;
}
var register_button = document.getElementById("register_button");
if (register_button !== null) {
register_button.onclick = validation;
}
for (i = 1; i <= 10; i++) {
var myErr = document.getElementById("err" + i);
if (myErr !== null) {
myErr.className = "error";
}
}
}
function validation() { /* you need some code here */ }
window.onload=init;
<h1>
Please Login
</h1>
<form id="order_form">
<fieldset>
<legend>Login</legend>
<div class="tab">
<div class="tRow">
<div class="tRow">
<div class="tCell">
<label for="user_name">User Name:</label>
</div>
<div class="tCell">
<input type="text" id="user_name" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow> <div class=">
<label for="password">Password:</label>
</div>
<div class="tCell">
<input type="text" id="password" required="" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="login_button" value="Login" />
</div>
</div>
<!--END OF THIS SELECTION-->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="register_button" value="Register Now!" />
</div>
</div>
<!--END OF THIS SELECTION-->
</div>
<!-- END OF THE TABLE -->
<br />
<div id="output" class="error"></div>
</fieldset>
</form>
You can make the test simpler:
var userPos = users.indexOf(aUser);
if (userPos !=-1 && userPos === pass.indexOf(aPass)) {
...
}