Check textarea is empty with queryselector - javascript

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

Related

ValidateForm How to validate and show text when submit button was clicked in JavaScript

I would like to show tick simple when the field is filled correctly, and show error message when it is not filled on each field.
I tried to make the code which using function validateForm, but it did not work. How do I fix the code? Please teach me where to fix.
Here is my html code
<form>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Name</p>
<input type="text"id="name">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required" >Required</span>Number</p>
<input type="text" id="number">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Mail address</p>
<input type="email">
</div>
<div class="Form-Item">
<p class="Form-Item-Label isMsg"><span class="Form-Item-Label-Required">Required</span>Message</p>
<textarea id="text"></textarea>
</div>
<input type="submit" value="submit">
<p id="log"></p>
</form>
Here is my JavaScript code
function validateForm(e) {
if (typeof e == 'undefined') e = window.event;
var name = U.$('name');
var number = U.$('number');
var email = U.$('email');
var text = U.$('text');
var error = false;
if (/^[A-Z \.\-']{2,20}$/i.test(name.value)) {
removeErrorMessage('name');
addCorrectMessage('name', '✔');
} else {
addErrorMessage('name', 'Please enter your name.');
error = true;
}
if (/\d{3}[ \-\.]?\d{3}[ \-\.]?\d{4}/.test(number.value)) {
removeErrorMessage('number');
addCorrectMessage('number', '✔');
} else {
addErrorMessage('number', 'Please enter your phone number.');
error = true;
}
if (/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/.test(email.value)) {
removeErrorMessage('email');
addCorrectMessage('email', '✔');
} else {
addErrorMessage('email', 'Please enter your email address.');
error = true;
}
if (/^[A-Z \.\-']{2,20}$/i.test(text.value)) {
removeErrorMessage('text');
addCorrectMessage('text', '✔');
} else {
addErrorMessage('text', 'Please enter your enquiry.');
error = true;
}
if (error) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
return false;
}
}
function addErrorMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Error';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'error';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'error';
}
}
function addCorrectMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Correct';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'Correct';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'Correct';
}
}
function removeErrorMessage(id) {
'use strict';
var span = document.getElementById(id + 'Error');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
function removeCorrectMessage(id) {
'use strict';
var span = document.getElementById(id + 'Correct');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
Using jQuery, you can use the .submit() event on a form element to conduct your own validation, note that you will have to preventDefault() to prevent the form submitting.
$("#myform").submit((e) => {
e.preventDefault(e);
// Validate name.
const name = $("#name").val();
if (name.length === 0) {
alert("Please provide a name!");
return;
}
alert("Success!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input type="text" id="name" placeholder="John Doe" />
<button type="submit">Submit</button>
</form>
which npm package do u use to validate ur data?.
If u use "validator" (link: https://www.npmjs.com/package/validator)
You can check if the field is filled correctly and send a check mark to the user.
for example if u wanted to check if data is an email
const validator = require("validator");
validator.isEmail('foo#bar.com');
if u want to see more about the options for the field just check the npm package page
Modern Browser support the Constraint Validation API which provides localized error messages.
Using this you can easily perform validation during basic events. For example:
// this will prevent the form from submit and print the keys and values to the console
document.getElementById("myForm").onsubmit = function(event) {
if (this.checkValidity()) {
[...new FormData(this).entries()].forEach(([key, value]) => console.log(`${key}: ${value}`);
event.preventDefault();
return false;
}
}
Would print all fields which would've been submitted to the console.
Or on an input field:
<input type="text" pattern="(foo|bar)" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());">
Will add the css class "valid" to the input field parent, if the value is foo or bar.
.valid {
border: 1px solid green;
}
.valid::after {
content: '✅'
}
<form oninput="this.querySelector('#submitButton').disabled = !this.checkValidity();" onsubmit="event.preventDefault(); console.log('Submit prevented but the form seems to be valid.'); return false;">
<fieldset>
<label for="newslettermail">E-Mail</label>
<!-- you could also define a more specific pattern on the email input since email would allow foo#bar as valid mail -->
<input type="email" id="newslettermail" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
</fieldset>
<fieldset>
<input type="checkbox" id="newsletterAcceptTos" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
<label for="newsletterAcceptTos">I accept the Terms of Service</label>
</fieldset>
<fieldset>
<label for="textFieldWithPattern">Enter <strong>foo</strong> or <strong>bar</strong></label>
<input type="text" id="textFieldWithPattern" pattern="^(foo|bar)$" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" >
</fieldset>
<button type="submit" id="submitButton" disabled>Submit</button>
<button type="submit">Force submit (will show errors on invalid input)</button>
</form>

JavaScript Custom Form Validation

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

Enable Disabled Button if Input is not empty

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

Validate required properties using javascript 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>

Display textbox multiple times

The HTML part contains a textarea with a label.The user has to enter text and the form should be submitted and refreshed for the user to enter text again for say 5 more times. How can I do this using Javascript?
This is the html code:
<form name="myform" method="post">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
</form>
<button type="button" class="btn" id="sub" onclick="func()">Next</button>
The javascript code:
var x=1;
document.getElementById("p1").innerHTML="Question"+x;
function func()
{
var frm = document.getElementsByName('myform')[0];
frm.submit();
frm.reset();
return false;
}
Here are two methods you can use. Both of these require you to add a submit button to your form, like this:
<form name="myform" method="post">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
<!-- add this button -->
<input type="submit" value="Submit" class="btn">
</form>
<!-- no need for a <button> out here! -->
Method 1: sessionStorage
sessionStorage allows you to store data that is persistent across page reloads.
For me info, see the MDN docs on sessionStorage. This method requires no external libraries.
Note that in this method, your page is reloaded on submit.
window.onload = function() {
var myForm = document.forms.myform;
myForm.onsubmit = function(e) {
// get the submit count from sessionStorage OR default to 0
var submitCount = sessionStorage.getItem('count') || 0;
if (submitCount == 5) {
// reset count to 0 for future submissions
} else {
// increment the count
sessionStorage.setItem('count', submitCount + 1);
}
return true; // let the submission continue as normal
}
// this code runs each time the pages loads
var submitCount = sessionStorage.getItem('count') || 0;
console.log('You have submited the form ' + submitCount + ' times');
if (submitCount == 4) {
console.log("This will be the final submit! This is the part where you change the submit button text to say \"Done\", etc.");
}
};
Method 2: AJAX with jQuery
If you don't mind using jQuery, you can easily make AJAX calls to submit your form multiple times without reloading.
Note that in this example your page is not reloaded after submit.
window.onload = function() {
var myForm = document.forms.myform;
var submitCount = 0;
myForm.onsubmit = function(e) {
$.post('/some/url', $(myForm).serialize()).done(function(data) {
submitCount++;
});
console.log('You have submited the form ' + submitCount + ' times');
if (submitCount == 4) {
console.log("This will be the final submit! This is the part where you change the submit button text to say \"Done\", etc.");
}
e.preventDefault();
return false;
};
};
Hope this helps!
You shuld create an array and push the value of the textbox to the array in func().
We can create a template using a <script type="text/template>, then append it to the form each time the button is clicked.
const btn = document.getElementById('sub');
const appendNewTextArea = function() {
const formEl = document.getElementById('form');
const textareaTemplate = document.getElementById('textarea-template').innerHTML;
const wrapper = document.createElement('div');
wrapper.innerHTML = textareaTemplate;
formEl.appendChild(wrapper);
}
// Call the function to create the first textarea
appendNewTextArea();
btn.addEventListener('click', appendNewTextArea);
<form name="myform" method="post" id="form">
</form>
<button type="button" class="btn" id="sub">Next</button>
<script id="textarea-template" type="text/template">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
</script>

Categories