Button don't disable on checkboxes validation - javascript

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;
}
});
})

Related

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.

Push notice not being read

I am trying to get the push notices visible upon pressing the button, depending on your age either of the "You are of legal age" or "You are not of legal age" messages should be written out depending on the age input by the user, if all previous inputs are filled and password is correct.
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 = [];
let users = [];
if (UNameInput.value === '' || UNameInput.value === null) {
feedback.push('Name input missing')
}
else 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 (ageElement.value < 18) {
feedback.push ("You are not of 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">
<title>Inlämningsuppgift</title>
<script src="JSny copy.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>
Updated jsfiddle: (Added name and age input to push message along with the legal notifcation)
jsfiddle
You need to put AgeInput.value !== '' at the end of if else condition. Also, I remove the iteration of the feedback.push()
else if(AgeInput.value !== ''){
if (ageElement.value < 18) {
feedback.push ("You are not of legal age")
}else {
feedback.push("You are of legal age")
}
}
Why are you iterating feedback in your else statement?
When feedback array is empty (and it is when your code enters else statement) there is nothing that it can iterate over so it doesn't check if (ageElement.value < 18) hence no output.
const nameElement = document.getElementById("UNameInput");
const ageElement = document.getElementById("AgeInput");
const passwordElement = document.getElementById("PasswordInput");
const faultElement = document.getElementById("errorOutput");
const clickElement = document.getElementById("button");
clickElement.addEventListener("click", function (e) {
const feedback = [];
if (nameElement.value === '' || nameElement.value === null) {
feedback.push('Name input missing');
} else if (ageElement.value === '' || ageElement.value === null) {
feedback.push('Age input missing');
} else if (passwordElement.value !== 'IHM') {
feedback.push('Password is not valid');
} else {
if (ageElement.value < 18) {
feedback.push("You are not of 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">
<title>Inlämningsuppgift</title>
</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>

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>

form validation dynamic created not working

I have some fields (created dynamically) in a page and I am trying to each element on form submit .Bellow code is sample ,only txtAge field validate, txtName not validating .Is there any option to validate each field with bellow code?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script>
function txtName_FormValidation() {
document.getElementById('entryForm').onsubmit = function (e) {
if (document.getElementById('txtName').value.length <= 0) {
alert(1)
document.getElementById('span_txtName').innerHTML = 'Please Enter Name.'
return false;
};
}
}
function txtAge_FormValidation() {
document.getElementById('entryForm').onsubmit = function (e) {
if (document.getElementById('txtAge').value.length <= 0) {
alert(2)
document.getElementById('span_txtAge').innerHTML = 'Please Enter Age.'
return false;
};
}
}
</script>
</head>
<body onload="txtName_FormValidation(); txtAge_FormValidation()">
<form id="entryForm">
<input type="text" id="txtName" />
<span id="span_txtName"></span>
<br />
<input type="text" id="txtAge" />
<span id="span_txtAge"></span>
<br />
<button type="submit" value="Sebmit">Submit</button>
</form>
</body>
</html>
Why don't you do like this?
calling all validations from same function?
<script>
document.getElementById('entryForm').onsubmit = function(e){
txtName_FormValidation(e);
txtAge_FormValidation(e);
}
function txtName_FormValidation(e) {
if (document.getElementById('txtName').value.length <= 0) {
alert(1)
document.getElementById('span_txtName').innerHTML = 'Please Enter Name.'
return false;
};
}
function txtAge_FormValidation(e) {
if (document.getElementById('txtAge').value.length <= 0) {
alert(2)
document.getElementById('span_txtAge').innerHTML = 'Please Enter Age.'
return false;
};
}
</script>
You are replacing the first onsubmit event, for this reason only dispatch the second function.
You can try this:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('entryForm').onsubmit = function (e) {
e.preventDefault();
if (document.getElementById('txtName').value.length <= 0) {
alert(1)
document.getElementById('span_txtName').innerHTML = 'Please Enter Name.'
};
if (document.getElementById('txtAge').value.length <= 0) {
alert(2)
document.getElementById('span_txtAge').innerHTML = 'Please Enter Age.'
};
}
}, false);
</script>
</head>
<body >
<form id="entryForm">
<input type="text" id="txtName" />
<span id="span_txtName"></span>
<br />
<input type="text" id="txtAge" />
<span id="span_txtAge"></span>
<br />
<button type="submit" value="Sebmit">Submit</button>
</form>
</body>
</html>

Categories