I am trying to change the display property of some text using JS, upon button click.
I have confirmed that the function is firing and running correctly using debugger, but for some reason, I can't grab the specific element I need to change, and assign it to a variable. I also have jquery set up on the page.
I have tried using the console, and document.getElementById('warning-textID') returns the correct element, but when I try to set it to a variable in console, it returns undefined. Am I missing something super obvious here?
Here is the HTML, function and css.
//adding event listener
$(function() {
document.getElementById("submitdiscount").addEventListener("click", putCookie);
});
// click function
function putCookie() {
var enteredValue = document.getElementById("nameBox").value;
var validParam = "test";
var warning = document.getElementById("warning-textID");
var cookieCreated = false;
if(enteredValue == validParam){
console.log('do the thing')
if(cookieCreated == false && enteredValue == validParam){
warning.innerText = "Please enable cookies";
warning.style.display = "";
return;
} else {
warning.innerText = "Please enter the correct code."
warning.style.display = "";
enteredValue.value = "";
return;
}
}
.warning-text {
color: red; text-align: center;
margin-bottom: 0px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="employee-code-input-wrapper" id="employee-code-input">
<div class="employee-code-input-header">
<h2>Enter the employee code you received via email</h2>
</div>
<div class="search-bar emplyoee-code-input-input-wrapper" >
<input class="emplyoee-code-input-input" type="text" placeholder="Enter Employee Code" code="" id="nameBox" name="pass">
<button class="btn btn--submit-employee-form" value="Submit" id="submitdiscount" type="button">submit</button>
</div>
<h2 class="warning-text" id="warning-textID">
Please enter the correct code.
</h2>
</div>
I fixed some mistakes and it worked.
//adding event listener
$(function() {
document.getElementById("submitdiscount").addEventListener("click", putCookie);
// click function
function putCookie() {
var enteredValue = document.getElementById("nameBox").value;
var validParam = "test";
var warning = document.getElementById("warning-textID");
var cookieCreated = false;
if (enteredValue === validParam) {
console.log('do the thing')
if (cookieCreated == false && enteredValue === validParam) {
warning.innerText = "Please enable cookies";
warning.style.display = "block";
return;
}
} else {
warning.innerText = "Please enter the correct code."
warning.style.display = "block";
enteredValue.value = "";
return;
}
}
});
.warning-text {
color: red;
text-align: center;
margin-bottom: 0px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="employee-code-input-wrapper" id="employee-code-input">
<div class="employee-code-input-header">
<h2>Enter the employee code you received via email</h2>
</div>
<div class="search-bar emplyoee-code-input-input-wrapper">
<input class="emplyoee-code-input-input" type="text" placeholder="Enter Employee Code" code="" id="nameBox" name="pass">
<button class="btn btn--submit-employee-form" value="Submit" id="submitdiscount" type="button">submit</button>
</div>
<h2 class="warning-text" id="warning-textID">
Please enter the correct code.
</h2>
</div>
Related
i want to have multiple elements with same class that act independently, after 1 night of seeking if "forEach" has any 'forEach:active' i end up with code below, but i feel kind of little shame with 'nextSibling of parent of parent' but if is supported by atleast any modern browsers, then is better than nothing.
on codePen is working fine,as well as snippet here.
i wonder if i can find a better version in vanila js for it or if is there anything deprecated that i should change.
//get + button
const up = document.querySelectorAll('.up');
//tell to + to increase his previous frend value
[].forEach.call(up, function(element) {
element.addEventListener('click', function() {
this.previousElementSibling.value =
parseInt(this.previousElementSibling.value) + 1;
});
})
//get -
const down = document.querySelectorAll('.down');
//tell to - to decrease his next frend value && and hide
//dynamic
//input if == 0 && show firstAdd button
[].forEach.call(down, function(element) {
element.addEventListener('click', function() {
this.nextElementSibling.value =
parseInt(this.nextElementSibling.value) - 1;
if (this.nextElementSibling.value == 0) {
this.parentElement.parentElement.style.display = 'none';
this.parentElement.parentElement.nextElementSibling.style.display = 'initial';
}
});
})
//get firstAdd button
const fAdd = document.querySelectorAll('.firstAdd');
//tell to it to add dynamic input && to vanish itself after &&
//set input value = 1
[].forEach.call(fAdd, function(element) {
element.addEventListener('click', function() {
this.previousElementSibling.style.display = 'initial';
this.previousElementSibling.children[1].children[1].value = 1;
this.style.display = 'none'
});
})
.form-group {
width: 30%;
margin: 30px;
display: none;
}
.input-group {
flex-direction: row;
display: flex;
}
body {
background: #111;
}
<div class='one'>
<div class="form-group">
<label>value: </label>
<div class="input-group">
<button class="down">-</button>
<input type="text" class="myNumber" value='1'>
<button class="up">+</button>
</div>
</div>
<button class='firstAdd'>Add</button></div>
<br>
<div class='two'>
<div class="form-group">
<label>value: </label>
<div class="input-group">
<button class="down">-</button>
<input type="text" class="myNumber" value='1'>
<button class="up">+</button>
</div>
</div>
<button class='firstAdd'>Add</button></div>
Goodmorning everyone,
I have a problem with a script for validating a form.
Given that the module has server-side validation in PHP, what I want to achieve, too, is client-side validation.
This validation is very simple.
When you click on the SUBMIT button, you must check if all the mandatory fields have been filled in.
If they are not:
must add a class to the input to make it change color;
must change the content of the icon next to the input field.
I use this script which works with regards to check and class on input. However, it uses a check on the NAME of the fields.
HTML
<form id="signinform" method="post" action="" class="wp-user-form" autocomplete="off" onsubmit="event.preventDefault(); validateMyForm();" novalidate>
<div class="msc-login-form-input">
<input type="text" name="log" value="" size="20" id="user_login" placeholder="Username o Email" autocomplete="off" required onkeyup="validateElement(this)"/>
<span id="errorsign"></span> </div>
<div class="msc-login-form-input">
<input type="password" name="pwd" value="" size="20" id="user_pass" placeholder="Password" autocomplete="off" required onkeyup="validateElement(this)"/>
<span id="errorsign"></span> </div>
<div class="msc-login-form-input-sendh">
<input type="submit" id="submit-login" name="submit-login" value="" class="user-submit" />
</div>
</form>
JS
<script lang="javascript">
function validateMyForm(){
let isFormValid = true;
let elems = document.getElementsByName("namefield");
for(let i=0; i< elems.length; i++)
{
let elem = elems[i];
if(elem.value.length < 1)
{
if(isFormValid){
isFormValid = false;
}
}
validateElement(elem);
}
if(isFormValid)
{
document.getElementById("signinform").submit();
return true;
}
}
function validateElement(elem){
if(elem.value.length < 1)
{
elem.className = "errorClass";
}else{
elem.className = "okClass";
}
}
</script>
CSS
<style>
.msc-login-form-input input.okClass {
background-color: #ffffff;
color: #3F4254;
}
.msc-login-form-input input.errorClass {
background-color: #4d40ff;
color: #ffffff;
}
.msc-login-form-input #errorsign {
width: 35px;
background-color: rgba(0,0,0,0.05);
min-height: 100%;
align-items: center;
justify-content: center;
text-align: center;
display: flex;
}
.msc-login-form-input #errorsign::before {
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "\f100";
}
.msc-login-form-input #errorsign.fail::before {
content: "\f00d";
color:#4d40ff;
}
.msc-login-form-input #errorsign.okay::before {
content: "\f00c";
color:#FF1493;
}
</style>
The problem is that the NAMEs of my fields are not the same and therefore that loop cannot work.
How can I solve without duplicating the loop for each form field?
How can I also add the control on the class of the icon next to it?
Thank you.
If you don't want to use the builtin validation, I'd do it as follows
let formvalid = true;
//these are the divs surrounding your elements to be validated
let elements = document.getElementsByClassName("msc-login-form-input")
for (let i = 0; i < elements.length; i++) {
//this is the input to be validated
let input = elements[i].getElementsByTagName("input")[0];
//this is the span element holding the icon
let icon = elements[i].getElementsByTagName("span")[0];
let valid = validateElement(input);
//set the classes input and span according to the validation result
input.classList.Add(valid ? "okClass" :"errorClass");
span.classList.Add(valid ? "okay" :"fail");
input.classList.Remove(valid ? "errorClass": "okClass");
span.classList.Remove(valid ? "fail" : "okay" );
//the form is only valid if ALL elements are valid
formvalid &= valid;
}
function validateElement(element) {
if (input.value.length === 0) return false;
//any other validations you want to do
return true;
}
Furhtermore you have a problem in your DOM tree. You have mutliple <span> elements with the same id="errorsign". That's not gonna work, because an id has to be unique. So remove the ids and grab the <spans> from their parents as shown above.
You could also just add the "okay" and "fail" to the surrounding <div> and adapt your css accordingly. Ie something like the following CSS
.msc-login-form-input.okay input {
...
}
.msc-login-form-input.fail input {
...
}
.msc-login-form-input.okay span::before {
...
}
.msc-login-form-input.fail span::before {
...
}
And the following JS
let formvalid = true;
//these are the divs surrounding your elements to be validated
let elements = document.getElementsByClassName("msc-login-form-input")
for (let i = 0; i < elements.length; i++) {
//this is the input to be validated
let input = elements[i].getElementsByTagName("input")[0];
let valid = validateElement(input);
element.classList.Add(valid ? "okay" : "fail");
element.classList.Remove(valid ? "fail": "okay");
formvalid &= valid;
}
I want to show the error message of required if mandatory fields are left blank. I implement it using the following way but every time the function checkinput() is invoked it adds a new span element due to which "required" message is outputted multiple times. I want the span element to be added once and disappears when user fills in the requirement. Here is my code.
const checkinput=(event)=>{
if(event.target.value===""){
event.target.insertAdjacentHTML('afterend','<span class="text-danger">Required</span>')
}
if(event.target.value!==""){
var child=document.querySelector('span');
child.remove();
}
}
document.getElementById("username").addEventListener('blur',checkinput);
document.getElementById("password").addEventListener('blur',checkinput);
document.getElementById("confirmPassword").addEventListener('blur',checkinput);
Reason why new span element is added each time you have a empty input field is because you are calling insertAdjacentHTML each time and inserting a new span element.
What you should do is add span elements with each input field in the html and initially they should be empty.When you want to validate the input fields, if any of the input is empty, select the span element next to that input element and show the error message in that span element using .textContent property. To clear the error message, you just need to set .textContent of the span element to an empty string.
Following code snippets show different ways of validating form inputs.
Form validation on form submit
Following code snippet validates form inputs when form is submitted.
const form = document.querySelector('form');
const usernameError = document.querySelector('#usernameError');
const passwordError = document.querySelector('#passwordError');
form.addEventListener('submit', (event) => {
event.preventDefault();
const usernameValid = validateField(form, 'username', usernameError);
const passwordValid = validateField(form, 'password', passwordError);
if (usernameValid && passwordValid) {
console.log('form submitted');
form.reset();
}
});
function validateField(form, fieldName, errorEl) {
if (form.elements[fieldName].value == '') {
errorEl.textContent = `${fieldName} is required`;
return false;
} else {
errorEl.textContent = '';
return true;
}
}
form div {
margin: 0 0 10px;
display: flex;
flex-direction: column;
max-width: 200px;
}
form label { margin: 0 0 5px; }
span { color: red; }
<form>
<div>
<label>Username</label>
<input type="text" name="username" />
<span id="usernameError"></span>
</div>
<div>
<label>Password</label>
<input type="password" name="password" />
<span id="passwordError"></span>
</div>
<button>Submit</button>
</form>
Form validation on input focus loose
Following code snippet validates form inputs when any of the input looses focus.
const form = document.querySelector('form');
const inputsContainer = document.getElementById('formInputsContainer');
const submitBtn = document.querySelector('button');
form.addEventListener('submit', (event) => {
event.preventDefault();
const usernameValid = validateField(form, 'username');
const passwordValid = validateField(form, 'password');
if (usernameValid && passwordValid) {
console.log('form submitted');
form.reset();
}
});
submitBtn.addEventListener('focus', () => {
form.requestSubmit();
});
inputsContainer.addEventListener('focusout', (event) => {
validateField(form, event.target.name);
});
function validateField(form, fieldName) {
const errorEl = document.getElementById(`${fieldName}Error`);
if (form.elements[fieldName].value == '') {
errorEl.textContent = `${fieldName} is required`;
return false;
} else {
errorEl.textContent = '';
return true;
}
}
form div {
margin: 0 0 10px;
display: flex;
flex-direction: column;
max-width: 200px;
}
form label { margin: 0 0 5px; }
span { color: red; }
<form>
<div id="formInputsContainer">
<div>
<label>Username</label>
<input type="text" name="username" />
<span id="usernameError"></span>
</div>
<div>
<label>Password</label>
<input type="password" name="password" />
<span id="passwordError"></span>
</div>
</div>
<button>Submit</button>
</form>
Form validation as user types in the input field
Following code snippet validates form input as user types in any input field.
const form = document.querySelector('form');
const inputsContainer = document.getElementById('formInputsContainer');
form.addEventListener('submit', (event) => {
event.preventDefault();
const usernameValid = validateField(form, 'username');
const passwordValid = validateField(form, 'password');
if (usernameValid && passwordValid) {
console.log('form submitted');
form.reset();
}
});
inputsContainer.addEventListener('input', (event) => {
validateField(form, event.target.name);
});
function validateField(form, fieldName) {
const errorEl = document.getElementById(`${fieldName}Error`);
if (form.elements[fieldName].value == '') {
errorEl.textContent = `${fieldName} is required`;
return false;
} else {
errorEl.textContent = '';
return true;
}
}
form div {
margin: 0 0 10px;
display: flex;
flex-direction: column;
max-width: 200px;
}
form label { margin: 0 0 5px; }
span { color: red; }
<form>
<div id="formInputsContainer">
<div>
<label>Username</label>
<input type="text" name="username" />
<span id="usernameError"></span>
</div>
<div>
<label>Password</label>
<input type="password" name="password" />
<span id="passwordError"></span>
</div>
</div>
<button>Submit</button>
</form>
You need something like
if(event.target.value==="" && document.querySelector('span') === null){
event.target.insertAdjacentHTML('afterend','<span class="text-danger">Required</span>')
}
if(event.target.value!==""){
var child=document.querySelector('span');
child.remove();
}
You only want to add a span IF the value is an empty string AND the span hsan't been added yet.
You can use this code which create a span which is add to the DOM with the ID which is based on the form element'sname attribute. And that element can be refered to based on the ID which was attach to it before It's been add to the DOM
const checkinput=(event)=>{
if(event.target.value===""){
let spanId = `input-${event.target.name}`
let span = `<span id="${spanId}" class="text-danger">Required</span>`
setTimeout(() =>{
document.getElementById(spanId).remove();
}, 5000);
event.target.insertAdjacentHTML('afterend',span)
}
}
document.getElementById("username").addEventListener('blur',checkinput);
document.getElementById("password").addEventListener('blur',checkinput);
document.getElementById("confirmPassword").addEventListener('blur',checkinput);
<form>
<input type="text" name="username" id="username"/>
<input type="text" name="password" id="password"/>
<input type="text" name="confirmPassword" id="confirmPassword"/>
</form>
May it help
<style>
.errorMsg {
border: 1px solid red;
}
.err {
color: red;
}
</style>
<form>
<input type="text" name="name" id="name">
<input type="password" name="password" id="password">
<button id="submit" type="submit">Submit</button>
</form>
<script>
let nameTag = document.querySelector('#name');
let passwordTag = document.querySelector('#password');
let submitBtn = document.querySelector('#submit');
nameTag.addEventListener('blur', e => validation(e));
passwordTag.addEventListener('blur', e => validation(e));
function validation(e) {
if (e.target.value == '') {
e.target.classList.add('errorMsg')
submitBtn.setAttribute('disabled', true) // Disable submit that user cannot submit
e.target.insertAdjacentHTML('afterend', `<span class="err ${e.target.id}">It is required</span>`)
// In the above line we are inserting an element with class same as id of input that in the remove we remove a particular error message only
} else {
e.target.classList.remove('errorMsg')
submitBtn.removeAttribute('disabled')
document.querySelector(`.err.${e.target.id}`).remove();
//Here code is saying that the element with if 'err' and 'class same as id of input' if both class present then remove it
}
}
</script>
Adding the class = id that a special error message delete
I have created a QR code generator. The user can create multiple QR codes.
I would like the user to be able to name each QR code (referred to as a checkpoint) by writing the desired checkpoint name in the text input field, clicking the Assign Name button and having the text input field disappear, being replaced by the name the user typed into the field.
The user can input checkpoint names, however, it only works for the first QR code printed, and the label only appears below the QR code. Below is the code that I have so far. Any help or suggestions to help me get the ball rolling on this would be very much appreciated. Thank you!
Note: If you try to run this to see the QR codes, you will have to enter something in the text field and press generate. They won't appear automatically.
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: arial, sans-serif;
}
section {
margin: 50px auto;
max-width: 350px;
text-align: center;
}
textarea {
width: 50%;
height: 50px;
margin-bottom: 10px;
}
#size {
max-width: 64px;
}
label {
display: inline-block;
width: 140px;
text-align: left;
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<section>
<h1>QR Code Generator</h1>
<p>Enter a URL or some text bellow and hit the Generate button (<kbd>Ctrl</kbd>+<kbd>Enter</kbd>)!</p>
<textarea id="textarea" autofocus></textarea>
<div class="block">
<label for="size">Size (px):</label>
<input align="left" id="size" type="number" value="150" min="50" max="500" step="50">
<label for="amount">Amount of Labels:</label>
<input align="left" id="amount" type="number" value="1" min="1" max="500" step="1">
<button id="genQRcode">Generate</button>
</div>
<div id="content" style="display: none;"></div>
</section>
<p id="demo" align="center"></p>
<script>
function myFunction() {
var x = document.getElementById("cpname").value;
document.getElementById("demo").innerHTML = x;
}
</script>
<script id="template-qr-code" type="text/html">
<p> <img id="qrcode" src="{{src}}" /></p>
<label for="checkpoint"> Checkpoint Name:</label>
<input id="cpname" type="text" value="">
<button onclick="myFunction()">Assign Name</button>
</script>
<script type="text/javascript">
window.addEventListener('load', function() {
var textarea = document.getElementById("textarea"),
content = document.getElementById("content"),
amount = document.getElementById("amount"),
qrTemplate = document.getElementById('template-qr-code');
function genQRcode() {
var data = encodeURIComponent(textarea.value),
size = document.getElementById("size").value,
chart = "http://chart.googleapis.com/chart?cht=qr&chs=" + size + "x" + size + "&choe=UTF-8&chld=L|0&chl=" + data;
if (data === "") {
alert("Please enter valid data!");
textarea.focus();
content.style.display = "none";
} else {
for (var i = 0; i < amount.value; i++) {
var qrSrc = qrTemplate.innerHTML;
qrSrc = qrSrc.replace(new RegExp('{{src}}', 'g'), chart);
qrSrc = qrSrc.replace(new RegExp('{{i}}', 'g'), i);
content.insertAdjacentHTML('beforeEnd', qrSrc);
}
content.style.display = "";
}
}
document.getElementById("genQRcode").addEventListener("click", genQRcode);
document.addEventListener("keydown", function(e) {
if (e.ctrlKey && e.keyCode == 13) {
genQRcode();
}
});
});
</script>
</body>
</html>
Your click function
function myFunction() {
var x = document.getElementById("cpname").value;
document.getElementById("demo").innerHTML = x;
}
is getting and setting an element by ID. That will only ever affect a single element on the page (usually the first one that the browser runs into with that specific id). You need to use a different selector / way of getting the label you want to change because you can't reuse ids.
Basically you need to make your label fields distinct so you can actually select them
I want to validate whatever the values of the inputs are using try and catch. Every time the user gives a wrong value I want a a message to appear next to the input box that filled wrong.
The problem is that the every time it executes, the wrong message appears in both input boxes and I don't want to put many conditions. I just want to make it as simple as possible. I don't have a clue what conditions I should use.
$(document).ready(function() {
$("#btn").click(function() {
var inputArr = [$("#name").val(), $("#lName").val()];
var regexArr = [new RegExp("\^[a-zA-z]+$"), new RegExp("\^[a-zA-z]+$")];
for (var i = 0; i < inputArr.length; i++) {
fn(regexArr[i], inputArr[i]);
} //for loop
function fn(exp, str) {
var res = exp.test(str);
try {
if (res == false) {
throw Error("wrong");
}
} catch (e) {
alert(e);
$("#empty1").fadeIn(3000);
$("#empty1").html(e);
$("#empty1").fadeOut(3000);
$("#empty2").fadeIn(3000);
$("#empty2").html(e);
$("#empty2").fadeOut(3000);
} //try and catch
} //function
}); //button
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
Name<input id="name"><span id="empty1"></span></br>
</br>
Last Name<input id="lName"><span id="empty2"></span></br>
</br>
<button id='btn'>Click</button>
</body>
</html>
For form validations, its better using Jquery validation plugin. It is very simple and needs Jquery library included in it. Try this https://jqueryvalidation.org/. Please refer this js fiddle also https://jsfiddle.net/jfc62uof/6/
<form action="javascript:void(0)" id="myform" role="form" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label><b>Password</b></label>
<input type="password" class="form-control" placeholder="Password" name="psw" id="psw">
</div>
<div class="form-group">
<label><b>Repeat Password</b></label>
<input type="password" class="form-control" placeholder="Repeat Password" name="rpsw">
<span id='message'></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" name="submit" value="save">
</div>
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>
<script>
$("#myform").validate({
rules: {
psw: {
required: true
},
rpsw: {
equalTo: "#psw"
}
}
});
</script>
Since you want it according to what has been asked of you to do,
$(document).ready(function() {
$("#btn").click(function() {
var inputArr = [$("#name").val(), $("#lName").val()];
var regexArr = [new RegExp("\^[a-zA-z]+$"), new RegExp("\^[a-zA-z]+$")];
for (var i = 0; i < inputArr.length; i++) {
fn(regexArr[i], inputArr[i],i+1);
} //for loop
function fn(exp, str, no) {
var res = exp.test(str);
try {
if (res == false) {
throw Error("wrong");
}
} catch (e) {
//alert(e);
if($('#err').length==0)
$("#empty"+no).val('').addClass('error').after('<p style="display:inline;" id="err">'+e+'</p>');
} //try and catch
} //function
}); //button
});
where error class can have css like
.error{
border: 2px solid red;
background-color: #f7b9d9;
}