I created function where I block all my inputs( I did it with for of loop). Now I would like to add condition if button checked unblock, if not checked block.
I wrote following code:
<div class="container">
<input type="number" class="block">
<input type="text" class="block">
<input type="email" class="block">
<input type="checkbox" id="scale1" name="scales">
<label for="scales">Scales</label>
</div>
function blockFileds() {
let inputsForm = document.getElementsByClassName('block');
let checker = document.getElementById('scale1');
for (const singleField of inputsForm) {
if (checker.checked) {
singleField.disabled = false;
} else {
singleField.disabled = true;
}
}
}
blockFileds()
input are blocked, but I cant' unblock it.
Remove the elements from the function,
And attach addEventListener to the input
let inputsForm = document.getElementsByClassName('block');
let checker = document.getElementById('scale1');
function blockFileds() {
for (let singleField of inputsForm) {
if (checker.checked) {
singleField.disabled = false;
} else {
singleField.disabled = true;
}
}
}
blockFileds()
checker.addEventListener("click", (e)=>{
blockFileds()
})
this way...
const
inputsForm = document.querySelectorAll('input.block')
, checker = document.querySelector('#scale1')
;
blockFileds()
checker.onclick = blockFileds
function blockFileds()
{
inputsForm.forEach( singleField =>
{
singleField.disabled = !checker.checked
})
}
.block, label {
display : block;
margin : .3em 0;
}
<div class="container">
<input type="number" class="block">
<input type="text" class="block">
<input type="email" class="block">
<label>
<input type="checkbox" id="scale1" name="scales">
Scales
</label>
</div>
you can try this:
const inputsForm = document.getElementsByClassName("block");
const checker = document.getElementById("scale1");
function blockFileds() {
for (let singleField of inputsForm) {
if (!checker.checked) {
singleField.disabled = "";
} else {
singleField.disabled = true;
}
}
}
checker.onclick = () => {
blockFileds();
}
Related
i made a login system with JavaScript for a game idea i had, but apparently my ide says it is too complex, do i need to split one function in more pieces? Do it reduces computer processing time? I just don't know if it's critical or not.
Anyway this is the code:
class Log {
constructor() {
this.list = {
username: ["admin", "helper"],
password: ["admin", "h24"]
};
this.user = document.getElementById('username');
this.psw = document.getElementById('password');
this.posUser = null;
this.posPsw = null;
this.t = true;
}
login() {
if (this.user.value != '' && this.user.value != null) {
if (!this.list.username.includes(this.user.value.toLowerCase())) {
errors.innerHTML = 'This user does not exist.';
} else {
for (let i = 0; i < this.list.username.length; i++) { //user[pos]
let j = this.user.value.toLowerCase();
if (j === this.list.username[i]) {
this.posUser = i;
}
}
for (let k = 0; k < this.list.password.length; k++) { //psw[pos]
let l = this.psw.value;
if (l === this.list.password[k]) {
this.posPsw = k;
}
}
if (this.posUser === this.posPsw) {
//access
console.log('access');
} else { // user[pos] != psw[pos] then show error
errors.innerHTML = 'Incorrect password.';
}
}
}
}
}
let errors = document.querySelector('.error');
let invite = new Log();
document.querySelector('.btnLog').addEventListener('click', function() {
invite.login();
});
* {
margin: 5px;
}
<div class="form">
<div class="inline">
<label>user</label><input type="text" id="username" autocomplete="off" />
</div>
<div class="inline">
<label>psw</label><input type="password" id="password" autocomplete="off" />
<div class="eye"></div>
</div>
<div class="flex-start">
<button class="btn btnLog">login</button>
</div>
<div class="inline none -error">
<div class="err_img"></div>
<div class="error"></div>
</div>
</div>
If your IDE uses Sonar to compute the cognitive complexity i suggest you to break up your code in multiple method calls
read this blog post to find out more https://blog.sonarsource.com/cognitive-complexity-because-testability-understandability
my original question got answered but I realize that every time I try to push user data in the arrays it wouldn't allow me to do is there any another to append data to arrays or is the push method the only way. or should i create a new array................................................................
"use strict"
const names = ["Ben", "Joel", "Judy", "Anne"];
const scores = [88, 98, 77, 88];
const $ = selector => document.querySelector(selector);
const addScore = () => {
// get user entries
const name = $("#name").value;
const score = parseInt($("#score").value);
let isValid = true;
// check entries for validity
if (name == "") {
$("#name").nextElementSibling.textContent = "This field is required.";
isValid = false;
} else {
$("#name").nextElementSibling.textContent = "";
}
if (isNaN(score) || score < 0 || score > 100) {
$("#score").nextElementSibling.textContent = "You must enter a valid score.";
isValid = false;
} else {
$("#score").nextElementSibling.textContent = "";
}
if (isValid) {
names.push("#name");
scores.push("#score");
names[names.length] = name;
scores[scores.length] = score;
$("#name").value = "";
$("#score").value = "";
}
$("#name").focus();
};
// display scores
const displayScores = () => {
for (let i = 0; i < names.length; i++) {
document.getElementById("scores_display").textContent += names[i] + " = " +
scores[i] +
"\n";
}
};
document.addEventListener("DOMContentLoaded", () => {
$("#add").addEventListener("click", addScore);
$("#display_scores").addEventListener("click", displayScores())
$("#name").focus();
});
<main>
<h1>Use a Test Score array</h1>
<div>
<label for="name">Name:</label>
<input type="text" id="name">
<span></span>
</div>
<div>
<label for="score">Score:</label>
<input type="text" id="score">
<span></span>
</div>
<div>
<label> </label>
<input type="button" id="add" value="Add to Array">
<input type="button" id="display_scores" value="Display Scores">
</div>
<div>
<textarea id="scores_display"></textarea>
</div>
</main>
All my previous notes were incorrect. Your adhoc $ const threw me off! My apologies.
The issue was you weren't calling displayScores() after updating the array. Plus, I added a line to that function to clear the existing text before looping through your data.
"use strict"
const names = ["Ben", "Joel", "Judy", "Anne"];
const scores = [88, 98, 77, 88];
const $ = selector => document.querySelector(selector);
const addScore = () => {
// get user entries
const name = $("#name").value;
const score = parseInt($("#score").value);
let isValid = true;
// check entries for validity
if (name == "") {
$("#name").nextElementSibling.textContent = "This field is required.";
isValid = false;
} else {
$("#name").nextElementSibling.textContent = "";
}
if (isNaN(score) || score < 0 || score > 100) {
$("#score").nextElementSibling.textContent = "You must enter a valid score.";
isValid = false;
} else {
$("#score").nextElementSibling.textContent = "";
}
if (isValid) {
names.push("#name");
scores.push("#score");
names[names.length] = name;
scores[scores.length] = score;
$("#name").value = "";
$("#score").value = "";
// add to the textarea
displayScores()
}
$("#name").focus();
};
// display scores
const displayScores = () => {
document.getElementById("scores_display").textContent = "";
for (let i = 0; i < names.length; i++) {
document.getElementById("scores_display").textContent += names[i] + " = " +
scores[i] +
"\n";
}
};
document.addEventListener("DOMContentLoaded", () => {
$("#add").addEventListener("click", addScore);
$("#display_scores").addEventListener("click", displayScores())
$("#name").focus();
});
<main>
<h1>Use a Test Score array</h1>
<div>
<label for="name">Name:</label>
<input type="text" id="name">
<span></span>
</div>
<div>
<label for="score">Score:</label>
<input type="text" id="score">
<span></span>
</div>
<div>
<label> </label>
<input type="button" id="add" value="Add to Array">
<input type="button" id="display_scores" value="Display Scores">
</div>
<div>
<textarea rows="6" id="scores_display"></textarea>
</div>
</main>
I'm trying to validate an input field. When i try to submit without filling in something, it gives me the error i made: please start your question with: will i ever. So i'm trying to check wether the text that the user types into the field, starts with: will i ever.
However, when i type a single (or more) random character(s), it just submits the form. I want it to check if the input starts with those fixed tree words, otherwise, no submission.
{
const handleSubmitForm = e => {
const $form = e.currentTarget;
if (!$form.checkValidity()) {
e.preventDefault();
const field = $form.querySelector('.question_field');
showValidationInfo(field);
//$form.querySelector('.error').innerHTML = 'Some errors occured';
} else {
console.log('Form is valid => submit form');
}
};
const showValidationInfo = field => {
console.log(field);
let message;
if (field.validity.valueMissing) {
message = 'Please fill in a question starting with: Will i ever';
}
if (field.validity.typeMismatch) {
message = 'Type not right';
}
if (field.validity.rangeOverflow) {
const max = field.getAttribute('max');
message = 'Too big, max ${max}';
}
if (field.validity.rangeUnderflow) {
const min = field.getAttribute('min');
message = 'Too small, min ${min}';
}
if (field.validity.tooShort) {
const min = field.getAttribute('minlength');
message = 'Too short, minimum length is ${min}';
}
if (field.validity.tooLong) {
const max = field.getAttribute('maxlength');
message = 'Too long, maximum length is ${max}';
}
if (!field.value.toLowerCase().startsWith("will i ever")) {
message = 'Start your question with: Will i ever';
}
if (message) {
field.parentElement.querySelector('.error').textContent =
message;
field.parentElement.querySelector('.error').style.color = "red";
}
};
const handeInputField = e => {
const $field = e.currentTarget;
if ($field.checkValidity()) {
$field.parentElement.querySelector('.error').textContent = '';
if ($field.form.checkValidity()) {
$field.form.querySelector('.error').innerHTML = '';
}
}
};
const handeBlurField = e => {
const $field = e.currentTarget;
showValidationInfo($field);
};
const addValidationListeners = fields => {
fields.forEach($field => {
$field.addEventListener('input', handeInputField);
$field.addEventListener('blur', handeBlurField);
});
};
const init = () => {
const $form = document.querySelector('form');
$form.noValidate = true;
$form.addEventListener('submit', handleSubmitForm);
const fields = $form.querySelectorAll('.input');
addValidationListeners(fields);
};
init();
}
<div class="name_wrapper">
<form autocomplete="off" class="form_question" action="answer.html">
<label class="name question" for="name">Ask me a question</label>
<div class="question_wrapper">
<p class="error">Start your question with: Will i ever...</p>
<input class="field question_field" type="text" name="question" placeholder="Will i ever..." value="" required>
</div>
<input id="button" class="answr-btn btn-question" type="submit" value="answer it!">
<input autocomplete="false" name="hidden" type="text" style="display:none;">
</form>
</div>
This line makes no sense:
const fields = $form.querySelectorAll('.input');
There are no HTML elements with class="input" in your form.
Did you mean $form.querySelectorAll('input')?
The problem is how you are handling the validation, the key is in this line if (!$form.checkValidity()) { this will not check if your string starts with Will i ever you have to do it manually before the if, here you have an alternative solution:
{
const handleSubmitForm = e => {
const $form = e.currentTarget;
const field = $form.querySelector('.question_field');
//here we validate the form manually
const message = showValidationInfo(field);
//if a message is found we show the error on the DOM, if is undefined we have no errors and we can submit the form
if (message) {
e.preventDefault();
$form.querySelector('.error').innerHTML = message;
$form.querySelector('.error').style.color = "red";
} else {
console.log('Form is valid => submit form');
}
};
const showValidationInfo = field => {
if (field.validity.valueMissing) {
return 'Please fill in a question starting with: Will i ever';
}
if (field.validity.typeMismatch) {
return 'Type not right';
}
if (field.validity.rangeOverflow) {
const max = field.getAttribute('max');
return 'Too big, max ${max}';
}
if (field.validity.rangeUnderflow) {
const min = field.getAttribute('min');
return 'Too small, min ${min}';
}
if (field.validity.tooShort) {
const min = field.getAttribute('minlength');
return 'Too short, minimum length is ${min}';
}
if (field.validity.tooLong) {
const max = field.getAttribute('maxlength');
return 'Too long, maximum length is ${max}';
}
if (!field.value.toLowerCase().startsWith("will i ever")) {
return 'Start your question with: Will i ever';
}
return undefined;
};
const handeInputField = e => {
const $field = e.currentTarget;
if ($field.checkValidity()) {
$field.parentElement.querySelector('.error').textContent = '';
if ($field.form.checkValidity()) {
$field.form.querySelector('.error').innerHTML = '';
}
}
};
const handeBlurField = e => {
const $field = e.currentTarget;
showValidationInfo($field);
};
const addValidationListeners = fields => {
fields.forEach($field => {
$field.addEventListener('input', handeInputField);
$field.addEventListener('blur', handeBlurField);
});
};
const init = () => {
const $form = document.querySelector('form');
$form.noValidate = true;
$form.addEventListener('submit', handleSubmitForm);
const fields = $form.querySelectorAll('.input');
addValidationListeners(fields);
};
init();
}
<div class="name_wrapper">
<form autocomplete="off" class="form_question" action="answer.html">
<label class="name question" for="name">Ask me a question</label>
<div class="question_wrapper">
<p class="error">Start your question with: Will i ever...</p>
<input class="field question_field" type="text" name="question" placeholder="Will i ever..." value="" required>
</div>
<input id="button" class="answr-btn btn-question" type="submit" value="answer it!">
<input autocomplete="false" name="hidden" type="text" style="display:none;">
</form>
You have uncommented backtick at occured `;
I have an similar problem like this post: Validation with datalist
However the answer of FelDev is in JavaScript I need it in jquery .
I am new to jquery therefore it would be of great help if some can help.
In the following the answer of FelDev:
let btn = document.getElementById("btnSend");
let form = document.getElementById("zeForm");
let input = document.getElementById("zeInput");
let msg = document.getElementById("msg");
let allowedValues = ["atown", "btown", "ctown"]; // same values as the options in your datalist
btn.onclick = function() {
let allGood = false;
allowedValues.forEach(function(elm) {
if(elm === input.value) {
allGood = true;
return;
}
})
if(allGood) {
msg.innerHTML = "Success!!";
msg.style.color = "green";
//form.submit();
} else {
msg.innerHTML = "This value is not accepted";
msg.style.color = "red";
}
msg.style.display = "inline";
}
#msg {
display: none;
}
#btnSend {
display: block;
margin-top:1rem;
}
<form id="zeForm">
<input id="zeInput" type="text" list="typ" name="name" placeholder="gtown" >
<datalist id="typ">
<!-- notice the absence of a <select> here... -->
<option value="atown">atown</option>
<option value="btown">btown</option>
<option value="ctown">ctown</option>
</datalist>
</input>
<p id="msg"></p>
<button id="btnSend" type="button">send</button>
</form>
So do you need a translation?
So the jquery of this js is :
let btn = $("#btnSend");
let form = $("#zeForm");
let input = $("#zeInput");
let msg = $("#msg");
let allowedValues = ["atown", "btown", "ctown"]; // same values as the options in your datalist
btn.on('click' , function() {
let allGood = false;
allowedValues.each(function(index, element) {
if (element === input.value) {
allGood = true;
return;
}
})
if (allGood) {
msg.text("Success!!");
msg.attr('style',"color:green");
//form.submit();
} else {
msg.text("This value is not accepted";
msg.attr('style',"color:red");
}
msg.attr('style',"display:inline");
});
I'm creating a "Sign Up" form for my new website, but got a problem with a jQuery/JS function that is supposed to check for some conditions to be reached.
$(function checkform() {
if (this.is("#username")) {
var validchars = /^[a-zA-Z0-9\s]+$/;
var nameHasError;
if (this.val().length < 6 && this.val().length > 26) {
nameHasError = true;
this.parent("div").addClass("has-error");
} else if (!(validchars.test(this).val())) {
nameHasError = true;
this.parent("div").addClass("has-error");
} else {
nameHasError = false;
this.parent("div").removeClass("has-error");
};
} else if (this.is("#password")) {
var passHasError;
if (this.val().length < 5 && this.val().length > 45) {
passHasError = true;
this.parent("div").addClass("has-error");
} else {
passHasError = false;
this.parent("div").removeClass("has-error");
};
};
});
Here's the JSFiddle with HTML part (I'm using bootstrap on my website but preferred to set a specific class on the fiddle)
Best regards
You are mixing vanilla javascript with jquery syntax. this.is('#username') is not javascript.
Use this.id == "username" (vanilla js) instead
OR
$(this).is('#username') (jquery)
Take care with the scope in your functions
There are multiple issues in the code
You have defined the checkForm in $(), so the function will be available only inside the dom ready handler, so your onkeypress will throw an error
When dom ready handler invokes the function this will be the document object which does not have the is function
The character size validation should use || not &&
So, ti will be better to use a jQuery event handler with both the fields having their own validation function like
jQuery(function($) {
$('#username').on('keypress', function() {
var validchars = /^[a-zA-Z0-9\s]+$/;
var nameHasError = false;
var $this = $(this),
value = this.value;
if (value.length < 6 || value.length > 26) {
nameHasError = true;
} else if (!validchars.test(value)) {
nameHasError = true;
};
$this.parent("div").toggleClass("has-error", nameHasError);
});
$('#password').on('keypress', function() {
var passHasError = false;
var $this = $(this),
value = this.value;
if (value.length < 5 || value.length > 45) {
passHasError = true;
};
$this.parent("div").toggleClass("has-error", passHasError);
});
});
.has-error {
background-color: red;
}
.has-success {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" placeholder="Between 6 and 26 characters">
<span id="unameError"></span>
</div>
<br/>
<div class="">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
<span id="passError"></span>
</div>
</div>
function checkform() {
if ($(this).is("#username")) {
var validchars = /^[a-zA-Z0-9\s]+$/;
var nameHasError;
if ($(this).val().length < 6 || $(this).val().length > 26) {
nameHasError = true;
$(this).parent("div").addClass("has-error");
} else if (!(validchars.test($(this).val()))) {
nameHasError = true;
$(this).parent("div").addClass("has-error");
} else {
nameHasError = false;
$(this).parent("div").removeClass("has-error");
};
} else if ($(this).is("#password")) {
var passHasError;
if ($(this).val().length < 5 || $(this).val().length > 45) {
passHasError = true;
$(this).parent("div").addClass("has-error");
} else {
passHasError = false;
$(this).parent("div").removeClass("has-error");
};
};
}
$(function () {
$('input').on('keyup', checkform);
})
.has-error {
background-color: red;
}
.has-success {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" placeholder="Between 6 and 26 characters">
<span id="unameError"></span>
</div>
<br/>
<div class="">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
<span id="passError"></span>
</div>
</div>