I am new to JavaScript and tend to get stuck with some problems. I was trying to create a custom validation for a form, which consists from 4 inputs, but the code doesn't work for me. Does anyone have any ideas how can I fix it? Here is just one of the inputs:
<div class="inputWrapper">
<input class="formInput required type="text" name="Email" id="Email" placeholder="Email Address"/>
<img class="errorImg hidden" src="/images/icon-error.svg" />
<div id="emailError" class="errorMessage hidden">
<i>Email cannot be empty</i>
</div>
</div>
I also have two divs that should appear, when the input is submitted with error, before that they have a class "hidden" with display none.
"use strict";
const formInput = document.querySelector(`.formInput`);
const errorImg = document.querySelector(`.errorImg`);
const errorMessage = document.querySelector(`.errorMessage`);
const input = formInput.nodeValue;
const errorOccured = function () {
errorMessage.classList.remove(`hidden`);
errorImg.classList.remove(`hidden`);
};
form.addEventListener("submit", function () {
if (input === ``) {
errorOccured();
}
});
This is how the page looks like itself:
You should read input value in the event listener function
let form = document.querySelector("#form1");
form.addEventListener("submit", function (e) {
const input = formInput.value;
if (input === '') {
errorOccured();
e.preventDefault();
}
});
Related
I am trying to check if "textarea" is empty and if thats the case trigers a validation function. so far It works if I use an input but textarea doesnt have a value and queryselector doesnt get a value of it.
Javascript
const commentValidation = document.querySelectorAll("textarea").value;
const checkComment = () =>{
let valid = false;
const comment = commentValidation;
if(!isRequired(comment)){
showError(commentValidation, "Comment cannot be blank");
}else if(!isCommentValid(comment)){
showError(commentValidation,"comment is not valid")
}else{
showSuccess(commentValidation);
valid = true;
}
return valid;
};
const isCommentValid = (comment) =>{
const re = /[a-zA-Z]/;
return re.test(comment);
};
const showSuccess = (input) =>{
const formField = input.parentElement;
formField.classList.remove('error');
formField.classList.add('success');
const error = formField.querySelector('small');
error.textContent = '';
}
form.addEventListener('submit', function (e){
e.preventDefault();
let isCommentValid = checkComment(),
let isCommentValid
if (isFormValid){
}
});
HTML
<div class ="form-field">
<label for="comment">Send a comment</label>
<textarea id="commentID" name="comment" autocomplete="off"></textarea>
<small></small>
</div>
Any ideas how to use queryselector and check if user didnt put a comment.
You don't need a javascript validation. Just add required to the textarea, and the browser will handle everything for you.
<form onsubmit="return false">
<div class="form-field">
<label for="comment">Send a comment</label>
<textarea id="commentID" name="comment" autocomplete="off" required></textarea>
<small></small>
</div>
<button type="submit">Submit</button>
</form>
the submit property is a property of a button or form. but you are using a div.
change html
<form class ="form-field" id="form-div">
<label for="comment">Send a comment</label>
<textarea id="commentID" name="comment" autocomplete="off"></textarea>
<small></small>
</form>
here we convert div tag to form
add javascript
const form = document.getElementById("form-div");
and let's put a trigger
in javascript
form.addEventListener('keyup', function (e){
e.preventDefault();
if (e.key === 'Enter' || e.keyCode === 13) {
form.submit();
}
});
Press the enter key and the form will be sent.
Working Demo : Demo
I have a webpage written in React (but it should not be strictly relevant to that question) that is composed by several inputs, let's call them Name, Surname and Code.
To work quickly, the insertion of the code is done with a Barcode Scanner that works as external keyboard. My idea is that if some field is focused, the keypress is inserted in the focused input but, in case no input is focused, I want to automatically focus and fill the Code input.
Is there a way to that it easily?
let inputName = document.querySelector('input[name="name"]');
let inputSurname = document.querySelector('input[name="surname"]');
let inputCode = document.querySelector('input[name="code"]');
let focusedInput = null;
[inputName, inputSurname, inputCode].forEach((input) => {
input.addEventListener('blur', () => {
focusedInput = null;
});
input.addEventListener('focus', () => {
focusedInput = input;
});
});
document.body.addEventListener('keypress', () => {
if (focusedInput == null) {
inputCode.focus();
}
});
<div>
<label>Name</label>
<input type="text" name="name" />
</div>
<div>
<label>Surname</label>
<input type="text" name="surname" />
</div>
<div>
<label>Code</label>
<input type="text" name="code" />
</div>
const surnameInput = document.getElementById('surname-input');
... (= do for all inputs)
let activeInput;
surnameInput.onFocus = () => { activeInput = surnameInput };
...
surnameInput.OnBlur = () => { activeInput = undefined };
...
document.addEventListener('keypress', (ev) => {
const input = activeInput ?? codeInput;
input.value += valueOftheKey;
}
You'd obviously have to evaluate if the key that was pressed has a value which you can add to the input, but I think this should give you an Idea of what to do. I haven't tried it out though, so it might not completely work.
Also: I'm not sure if it's the most efficient way, but it's an option.
EDIT: Answer by Kostas is better ;) except for the null...you should use undefined
I have one simple form which have two fields called first name with id fname and email field with email. I have submit button with id called submit-btn.
I have disabled submit button using javascript like this
document.getElementById("submit-btn").disabled = true;
Now I am looking for allow submit if both of my fields are filled.
My full javascript is like this
<script type="text/javascript">
document.getElementById("submit-btn").disabled = true;
document.getElementById("submit-btn").onclick = function(){
window.open("https://google.com",'_blank');
}
</script>
I am learning javascript and does not know how I can do it. Let me know if someone here can help me for same.
Thanks!
Id propose something like this
Use a block, which encapsulates the names of variables and functions inside the block scope
Make small functions, which do just one thing
Prefer addEventListener over onclick or onanything
There are two types of events you could use on the inputs: input and change. input will react on every keystroke, check will only react, if you blur the input element
I added a check for validity to the email field with checkValidity method
{
const btn = document.getElementById("submit-btn");
const fname = document.getElementById("fname");
const email = document.getElementById("email");
deactivate()
function activate() {
btn.disabled = false;
}
function deactivate() {
btn.disabled = true;
}
function check() {
if (fname.value != '' && email.value != '' && email.checkValidity()) {
activate()
} else {
deactivate()
}
}
btn.addEventListener('click', function(e) {
alert('submit')
})
fname.addEventListener('input', check)
email.addEventListener('input', check)
}
<form>
<input type="text" name="" id="fname">
<input type="email" name="" id="email">
<input type="submit" id="submit-btn" value="Submit">
</form>
This is the simplest solution I can imagine:
myForm.oninput = () => {
btn.disabled = fname.value == '' || email.value == '' || !email.checkValidity();
}
<form id="myForm">
<input type="text" name="" id="fname">
<input type="email" name="" id="email">
<input type="submit" id="btn" value="Submit" disabled>
</form>
Personally, I prefer to use regex to check the e-mail, instead of checkValidity(). Something like this:
/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/.test(email.value);
I have html form with action ="script.php" which sends data.
I want prevent form to being sent with JS but it does nothing and sends data.
Naslov = title
This is html:
<form name = "my_form" enctype="multipart/form-data" method = "POST" action = "skripta.php">
<div class="form-group row ">
<div class="col-md-6">
<span id="porukaTitle" class="bojaPoruke"></span>
<label for="naslov">Naslov</label>
<input type="text" name="naslov" class="form-control" id="naslov">
</div>
</form>
And this is JS:
<script type="text/javascript">
document.getElementById("slanje").onclick = function (event) {
var slanjeForme=true;
var poljeTitle=document.getElementById("naslov");
var naslov=document.getElementById("naslov").value;
if (naslov.lenght < 5 || naslov.lenght > 30) {
slanjeForme=false;
poljeTitle.style.border="1px dashed red";
document.getElementById("porukaTitle").innerHTML="Naslov vjesti mora imati između 5 i 30 znakova!<br>";
} else {
poljeTitle.style.border="1px solid green";
document.getElementById( "porukaTitle").innerHTML="";
}
if (slanjeForme != true) {
event.preventDefault();
}
}
</script>
Problem is that it always sends data.
Don't use the "click" handler, instead use the FORM's "submit" Event handler!
Create a nifty reusable validate function that will also handle the input style using classList.toggle()
Populate your validate function with the needed validators
Use finally CSS to handle error borders and messages visibility using the class is-error
Always place the error SPAN elements as siblings to a desired action element, that way when an input gets the .is-error we can target it using the CSS's General Sibling Combinator ~
No matter how many inputs you have, you don't need to write extra JS logic. Just validate the desired ones like const has_err = validate(EL("#foo"), "length");
const validate = (el, validatorName = "length") => {
const val = el.value.trim();
const isErr = {
// Basic, validates if there's value
length: () => val.length < 1,
// Validate between 5 and 30 charaters
length_5_30: () => val.length < 5 || val.length > 30,
// Add more validators
}[validatorName]();
el.classList.toggle("is-error", isErr);
return isErr;
};
const EL = (sel, EL) => (EL || document).querySelector(sel);
EL("#my_form").addEventListener("submit", function(event) {
const err_1 = validate(EL("#naslov"), "length_5_30");
const err_2 = validate(EL("#bla"), "length");
if (err_1 || err_2) {
event.preventDefault();
}
});
form .is-error {
outline: 1px dashed red;
}
form .error-message {
display: none;
color: red;
}
form .is-error ~ .error-message {
display: block;
}
<form id="my_form" name="my_form" enctype="multipart/form-data" method="POST" action="skripta.php">
<div class="form-group row">
<div class="col-md-6">
<label for="naslov">Naslov</label>
<input type="text" id="naslov" name="naslov" class="form-control">
<span class="error-message">Naslov vjesti mora imati između 5 i 30 znakova!</span>
</div>
</div>
<div class="form-group row">
<div class="col-md-6">
<label for="naslov">Bla bla</label>
<input type="text" id="bla" name="bla" class="form-control">
<span class="error-message">Ovo polje ne može biti prazno!</span>
</div>
</div>
<button type="submit">Pošalji</button>
</form>
You should use a form validation function instead. In your form, add an attribute called "onsubmit". The form should look similar to this:
<form onsubmit="return checkBeforeSubmitting()"></form>
Then, you can have a function run before data is sent. If you don't want data to be sent, make the "checkBeforeSubmitting()" return false under a certain condition.
Link to more info on how to use this: https://www.w3schools.com/js/js_validation.asp
The best way to stop a form from submitted is to hook into its submit event, and do so in the javascript, rather than add javascript into the html. That would look like this:
var form = document.querySelector('form.myform');
form.addEventListener('submit', e => {
// put your conditional here
if( please_dont_submit == true ) {
e.preventDefault();
}
// else form will submit;
});
<form class="myform">
<!-- form stuff -->
<input type="submit" value="Submit">
</form>
You may also wish to submit the form from within itself, after doing the preventDefault(). You can do that by setting a flag to indicate that the check has already been processed:
const form = document.querySelector('form.myform');
var okToSubmit = false;
form.addEventListener('submit', e => {
// put your conditional here
if( please_dont_submit == true && ! okToSubmit ) {
e.preventDefault();
// do some further processing and submit again.
okToSubmit = true;
e.target.submit();
}
// else form will submit;
});
I submited a form using javascript (must check pre-condition first), and I noticed that I'm not notified about unfilled required properties:
function offerContract() // the function called when deployContractBtn is clicked
{
document.getElementById("CreateContractDialogMessage").innerHTML = "";
ErrorMsg = checkErrors();
if (ErrorMsg != "")
{
$('#CreateContractDialogTitle').text("Error"); //show error headline
document.getElementById("CreateContractDialogMessage").innerHTML = ErrorMsg;
document.getElementById("closeButton").style.display = "block";
$('#dialogOfferContract').modal('show');
return;
}
$("#deployContractBtn").submit() //type = button and not submit
}
#using (Html.BeginForm("DeployContract", "CreateContract", FormMethod.Post, new { #id = "DeployContractForm" }))
{
.....The rest of the form....
<input id="deployContractBtn" onclick="offerContract()" type="button" class="btn btn-success" value="Sign&Deploy Contract" disabled />
}
How to notify about the unfilled requierd properties using javascript as the classic submit does? Is it possible to mark them, so the user will know where he needs to insert values?
If you want to leverage default browser UI, you can just mark the field as required. By default, the form will now allow a user to submit it until the requirements are met.
<form id="myForm">
<input placeholder="this field is required" required />
<button type="submit">Submit</button>
</form>
However, If you want a little more customization you can use JavaScript to do what you want.
const submitBtn = document.getElementById('submit');
submitBtn.addEventListener('click', (e) => {
const form = document.getElementById('myForm');
if (form.checkValidity()) {
// TODO: Submit form code here
console.log('Form submitted');
return;
} else {
const nameField = document.getElementById('nameField');
if (!nameField.checkValidity()) {
alert('The Name Field is a required field. Please provude a valid value');
}
}
});
<form id="myForm">
<input placeholder="this field is required" id="nameField" required />
</form>
<button id="submit">Submit</button>