Keypress Event not woking in my JavaScript Code/ - javascript

Apologize me as I am a beginner and I am trying to Run my keypress Event but when I press the Enter key it is not responding need help.
Enterbtn.addEventListener("keydown",function(event){
if(input.value.length>0 && event.keycode === 13){
let li=document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
}

You've miswritten keyCode (capital letter)
(Edit: Maybe Enterbtn could also be a problem. Use window if you want the user to be able to trigger the event from anywhere)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<input id="myInput" type="text" value="" />
</head>
<body>
<script>
const myInputObj = document.getElementById("myInput");
window.addEventListener("keydown", function (event) {
if (myInputObj.value.length > 0 && event.keyCode === 13) {
console.log("do something");
}
});
</script>
</body>
</html>

I'm not sure what you're trying to achieve but this might help you.
Enter your value and press Enter.
const myInput = document.querySelector("input");
const myList = document.querySelector("ul");
myInput.addEventListener("keydown", (e) => {
if(e.key === "Enter") {
const myItem = document.createElement("li");
myItem.textContent = myInput.value;
myList.appendChild(myItem);
myInput.value = "";
}
});
<!DOCTYPE html>
<html>
<body>
<input style="width:50%;" type="text" placeholder ="Enter your value and press 'Enter'"></input>
<ul></ul>
</body>
</html>

May be this could be help full
const input = document.getElementById("input");
const ul = document.getElementById("sample-ul");
input.addEventListener("keydown", function (event) {
if (input.value.length > 0 && event.keyCode === 13) {
console.log(event.keyCode)
let li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
}
});
<input type="text" id='input' />
<ul id='sample-ul'></ul>

Related

Button don't disable on checkboxes validation

I have simple function where I have 3 checkboxes and trying to something like if are checkboxes unchecked, button should be disabled and if I check all (not just 1 or 2), button will activate
function sub() {
var a = document.getElementById("ch1");
var b = document.getElementById("ch2");
var c = document.getElementById("ch3");
var btn = document.getElementById("btn")
if (a.checked == true && b.checked == true && c.checked == true){
return btn.disabled = !!this.checked;
}
else {
return btn.disabled;
}
}
<!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">
<title>Test</title>
</head>
<body>
<input type="checkbox" id="ch1" >
<input type="checkbox" id="ch2" >
<input type="checkbox" id="ch3" >
<button onclick="sub()" id="btn">Submit</button>
</body>
<script>
</script>
</html>
You need to add an EventListener to the checkboxes and listen if their state change not add the script to a button itself:
let checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(el =>
el.addEventListener('change', function() {
let checked_checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
if (checked_checkboxes.length === checkboxes.length) {
document.querySelector('#btn').removeAttribute('disabled');
} else {
document.querySelector('#btn').setAttribute('disabled', true);
}
})
)
<!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">
<title>Test</title>
</head>
<body>
<input type="checkbox" id="ch1" >
<input type="checkbox" id="ch2" >
<input type="checkbox" id="ch3" >
<button onclick="sub()" id="btn" disabled>Submit</button>
</body>
<script>
</script>
</html>
You need to set your button to disabled using a boolean. Whatever you think this.checked is, that's the issue.
btn.disabled = false;
Also if the button is enabled, it will just disable and never re-check .. You need to run sub() on the checkbox click ..
function sub() {
var a = document.getElementById("ch1");
var b = document.getElementById("ch2");
var c = document.getElementById("ch3");
var btn = document.getElementById("btn")
if (a.checked == true && b.checked == true && c.checked == true) {
btn.disabled = false;
} else {
btn.disabled = true;
}
}
<input onclick="sub()" type="checkbox" id="ch1">
<input onclick="sub()" type="checkbox" id="ch2">
<input onclick="sub()" type="checkbox" id="ch3">
<button id="btn" disabled>Submit</button>
document.getElementById("ch1").checked = true;
document.getElementById("ch2").checked = true;
document.getElementById("ch3").checked = true;
var checkedCount = 3;
var checkboxes = document.querySelectorAll("input[name=checkbox]");
checkboxes.forEach(function(checkbox){
checkbox.addEventListener('change', function() {
if (this.checked) {
console.log("Checkbox is checked..");
checkedCount++;
console.log(checkedCount);
} else {
console.log("Checkbox is not checked..");
checkedCount--;
console.log(checkedCount);
}
if(checkedCount<3){
document.getElementById("btn").disabled = true;
}else{
document.getElementById("btn").disabled = false;
}
});
})

Need the output of the inputs to be pushed into the <div>

I'm trying to get the user inputs to be pushed out as a message into a <div> via the button press after confirming that all the inputs are filled and the correct password has been entered. That part works fine but my forEach is not working:
If the user has input a number value lower than 18, I want an if that types out via push "Your name is UName and you are Age years old, you are not of legal age", or else the same result as above but ending with "...you are of legal age".
Any idea how I should go forth?
let nameElement = document.getElementById("UNameInput");
let faultElement = document.getElementById("errorOutput");
let ageElement = document.getElementById("AgeInput");
let clickElement = document.getElementById("button");
let passwordElement = document.getElementById("PasswordInput");
clickElement.addEventListener("click", function(e) {
let feedback = [];
if (UNameInput.value === '' || UNameInput.value === null) {
feedback.push('Name input missing')
}
if (AgeInput.value === '' || AgeInput.value === null) {
feedback.push('Age input missing')
} else if (PasswordInput.value !== 'IHM') {
feedback.push('Password is not valid')
} else {
feedback.forEach((item, i) => {
if (item.AgeInput < 18) {
feedback.push("You are not of not legal age")
} else {
feedback.push(" You are of legal age ")
}
});
}
if (feedback.length > 0) {
e.preventDefault()
faultElement.innerText = feedback.join(", ")
}
});
<!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">
<script src="JSny.js" defer></script>
</head>
<body>
<div id="errorOutput"></div>
<p id="output"></p>
<div>
<label for="UNameInput">Name Input</label>
<input id="UNameInput" name="name" type="text">
</div>
<div>
<label for="AgeInput">Age Input</label>
<input id="AgeInput" name="age" type="number">
</div>
<div>
<label for="PasswordInput">Password Input</label>
<input id="PasswordInput" name="password" type="password">
</div>
<button id="button">Submit</button>
</body>
</html>
You are using AgeInput instead of ageElement in the if statement.

SubmitForm when pressing Enter (To-do-list)

I was building a To Do List with HTML and JavaScript and now I want to add input not only with the submit button but also if i press enter anywhere on the page. I mainly wanna use javascript only to create that function, no "onclick" feature in 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="style.css" />
<title>To do app</title>
</head>
<body>
<h1>To-Do List</h1>
<form>
<input type="text" placeholder="Add an item!" id="inputField" />
</form>
<button id="submit">Submit</button>
<button id="clear">Clear List</button>
<div id="output"></div>
<script src="script.js"></script>
</body>
</html>
----------------------------------
document.getElementById("submit").addEventListener("click", function () {
submitForm();
});
document.getElementById("clear").addEventListener("click", function () {
document.getElementById("inputField").value = "";
document.getElementById("myOl").innerHTML = "";
});
function submitForm() {
let input = document.getElementById("inputField").value;
let ol = document.createElement("ol");
ol.setAttribute("id", "myOl");
document.body.appendChild(ol);
let y = document.createElement("LI");
let t = document.createTextNode(`${input}`);
y.appendChild(t);
document.getElementById("myOl").appendChild(y);
document.getElementById("inputField").value = "";
}
You could use keypress event listner with document.addEventListener and check for the event.key, event.keyCode and event.which combination to check for enter key.
Dont forget to use event.preventDefault() to prevent reload of page.
document.getElementById("submit").addEventListener("click", function () {
submitForm();
});
document.getElementById("clear").addEventListener("click", function () {
document.getElementById("inputField").value = "";
document.getElementById("myOl").innerHTML = "";
});
document.addEventListener('keypress', function (e) {
const code = (e.keyCode ? e.keyCode : e.which);
if (e.key === 'Enter' || code == 13) {
submitForm();
e.preventDefault();
}
});
function submitForm() {
let input = document.getElementById("inputField").value;
let ol = document.createElement("ol");
ol.setAttribute("id", "myOl");
document.body.appendChild(ol);
let y = document.createElement("LI");
let t = document.createTextNode(`${input}`);
y.appendChild(t);
document.getElementById("myOl").appendChild(y);
document.getElementById("inputField").value = "";
}
<h1>To-Do List</h1>
<form>
<input type="text" placeholder="Add an item!" id="inputField" />
</form>
<button id="submit">Submit</button>
<button id="clear">Clear List</button>
<div id="output"></div>
You can use key up event.
document.addEventListener('keyup', keypress);
function keypress(e){
e.preventDefault()
if (e.key === 'Enter' || e.keyCode === 13) {
submitForm();
}
}
added e.preventDefault() to avoid form submission
https://developer.mozilla.org/en-US/docs/Web/API/Document/keyup_event

I want to return 'Alert' box if someone submits empty form

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>To Do List</h1>
<form>
<input autocomplete="off" autofocus id="todotext"
type="text">
<input onclick="serve(); return false" type="submit">
</form>
<ol id="add"></ol>
</body>
<script>
function serve(){
const neww = document.getElementById('add');
let text = document.getElementById('todotext').value;
const a = document.createElement('li');
a.innerText = text;
neww.appendChild(a);
document.getElementById('todotext').value = "";
}
</script>
</html>
Here is my code and I want to return an 'Alert' if someone submit empty form.
How should I do it ? Any help will be appreciated
Here's an image:
Is this what you want?
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>To Do List</h1>
<form>
<input autocomplete="off" autofocus id="todotext"
type="text">
<button onclick="todotext.value != '' ? serve() : alert('Input field is blank')" >Submit</button>
</form>
<ol id="add"></ol>
</body>
<script>
var todotext = document.getElementById('todotext');
function serve() {
const neww = document.getElementById('add');
let text = todotext.value;
const a = document.createElement('li');
a.innerText = text;
neww.appendChild(a);
document.getElementById('todotext').value = "";
}
</script>
</html>
String.prototype.isEmpty = function() {
return (this.length === 0 || !this.trim());
};
function serve(){
const neww = document.getElementById('add')
let text = document.getElementById('todotext').value;
if( text.isEmpty() ){
alert('cannot be blank');
return;
}
const a = document.createElement('li')
a.innerText = text
neww.appendChild(a)
document.getElementById('todotext').value = ""
}
<h1>To Do List</h1>
<form>
<input autocomplete="off" autofocus id="todotext"
type="text">
<input onclick="serve(); return false" type="submit">
</form>
<ol id="add"></ol>
add condition when append new element by checking the value of todoText
function serve(){
const neww = document.getElementById('add')
let text = document.getElementById('todotext').value
if(text == ""){
alert('field is required');
}
else{
const a = document.createElement('li')
a.innerText = text
neww.appendChild(a)
document.getElementById('todotext').value = ""
};
}
function serve(){
const neww = document.getElementById('add')
let text = document.getElementById('todotext').value
if(text.trim().length === 0){
alert("Field is empty");
}else{
const a = document.createElement('li')
a.innerText = text
neww.appendChild(a)
document.getElementById('todotext').value = ""
}
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>To Do List</h1>
<form>
<input autocomplete="off" autofocus id="todotext"
type="text">
<input onclick="serve(); return false" type="submit">
</form>
<ol id="add"></ol>
</body>
</html>

addEventListener click is immediately disappearing after KeyPress [duplicate]

This question already has answers here:
HTML button to NOT submit form
(9 answers)
Closed 4 years ago.
For some reason I can not get it to work, after clicking enter on the keyboard the new input shows up for less than a millisecond and then disappears
<!DOCTYPE html>
<html>
<head>
<title>Simple Register Form with JavaScript</title>
</head>
<body>
<form>
<input type="text" class="regFname" placeholder="First name: ">
<button>Register</button>
</form>
<p>Current Users</p>
<ul></ul>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
and here is the JavaScript
var inputFname = document.querySelector(".regFname");
var button = document.querySelector("button");
var ul = document.querySelector("ul");
function inputLength() {
return inputFname.value.length;
}
function add() {
var li = document.createElement("li");
li.appendChild(document.createTextNode(inputFname.value));
ul.appendChild(li);
inputFname.value = "";
}
function addUserAfterClick() {
if (inputLength() > 0) {
add();
}
}
function addUserAfterKeyPress(event) {
if (inputLength() > 0 && event.keyCode === 13) {
add();
}
}
button.addEventListener("click", addUserAfterClick);
inputFname.addEventListener("keypress", addUserAfterKeyPress);
Just add type="button" in your html. If not specified it behaves as type="submit"
var inputFname = document.querySelector(".regFname");
var button = document.querySelector("button");
var ul = document.querySelector("ul");
function inputLength() {
return inputFname.value.length;
}
function addUser() {
if (inputLength() > 0) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(inputFname.value));
ul.appendChild(li);
inputFname.value = "";
}
}
button.addEventListener("click", addUser);
<form>
<input type="text" class="regFname" placeholder="First name: ">
<button type="button">Register</button>
</form>
<p>Current Users</p>
<ul></ul>

Categories