Display error style with javascript using html 5 validations - javascript

I have a form with HTML validations and I am using JS to add or remove error style.
<form action="" id="addForm">
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" required minlength="3" />
</div>
<button type="submit">Add</button>
</form>
window.onload = handleLoad;
function handleLoad() {
const form = document.forms.addForm;
const name = form.name;
name.onkeyup = function () {
if (name.checkValidity()) {
name.classList.remove("error");
} else {
name.classList.add("error");
}
};
}
In this case the error class gets applied as the user is typing in the field. Is there a way to prevent this?

You are using the onkeyup event, which means the event is triggered every time the user releases a key.
If you want to check the input field only when the user moves to the next field, you could use the onfocusout event.
name.onkeyup = function () {
if (name.checkValidity()) {
name.classList.remove("error");
} else {
name.classList.add("error");
}
}
P.S., If you have a small form, you could also implement validation when the submit button is clicked.

Related

Conditionally required form field (Checkbox)

I already checked multiple sites and posts regarding this topic, but couldn't find an answer yet. I simply want to fire the following JS code if someone clicked a specific Checkbox in my form:
function updateRequirements() {
var escortWrapper = document.querySelector(".elementor-field-type-html .elementor-field-group .elementor-column .elementor-field-group-field_ceffa28 .elementor-col-100");
if (escortWrapper.style.display != 'none') {
document.getElementById('escort').required = true;
} else {
document.getElementById('escort').required = false;
}
}
You can check and test that for yourself on the following site:
Advelio Website
If you click on the second checkbox field, there is a field appearing where you can type in your name. And this field is currently optional, but I want to make this required if someone clicked the second checkbox.
You can do it like this:
function updateRequirements() {
const btn = document.getElementById('escort');
btn.required = !btn.required;
}
document.querySelector("#requireCheck").addEventListener('click', updateRequirements);
<form>
<input type="checkbox" id="requireCheck">
<label for="requireCheck">Should the the other input be required?</label>
<br>
<input type="text" id="escort">
<input type="submit" value="submit">
</form>
I simplified the function updateRequirements for the scope of this answer, but it can be changed to anything or any condition.
You have to have event listener for click event and if you dont have create one and wrote the function with logic what to do if is click

JS - Collecting data from one function to run in another [duplicate]

There seems to be lots of info on how to submit a form using javascript, but I am looking for a solution to capture when a form has been submitted and intercept it in javascript.
HTML
<form>
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
When a user presses the submit button, I do not want the form to be submitted, but instead I would like a JavaScript function to be called.
function captureForm() {
// do some stuff with the values in the form
// stop form from being submitted
}
A quick hack would be to add an onclick function to the button but I do not like this solution... there are many ways to submit a form... e.g. pressing return while on an input, which this does not account for.
Ty
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
In JS:
function processForm(e) {
if (e.preventDefault) e.preventDefault();
/* do what you want with the form */
// You must return false to prevent the default form behavior
return false;
}
var form = document.getElementById('my-form');
if (form.attachEvent) {
form.attachEvent("submit", processForm);
} else {
form.addEventListener("submit", processForm);
}
Edit: in my opinion, this approach is better than setting the onSubmit attribute on the form since it maintains separation of mark-up and functionality. But that's just my two cents.
Edit2: Updated my example to include preventDefault()
You cannot attach events before the elements you attach them to has loaded
It is recommended to use eventListeners - here one when the page loads and another when the form is submitted
This works since IE9:
Plain/Vanilla JS
// Should only be triggered on first page load
console.log('ho');
window.addEventListener("DOMContentLoaded", function() {
document.getElementById('my-form').addEventListener("submit", function(e) {
e.preventDefault(); // before the code
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
})
});
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
jQuery
// Should only be triggered on first page load
console.log('ho');
$(function() {
$('#my-form').on("submit", function(e) {
e.preventDefault(); // cancel the actual submit
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
Not recommended but will work
If you do not need more than one event handler, you can use onload and onsubmit
// Should only be triggered on first page load
console.log('ho');
window.onload = function() {
document.getElementById('my-form').onsubmit = function() {
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
// You must return false to prevent the default form behavior
return false;
}
}
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
<form onSubmit="return captureForm()">
that should do. Make sure that your captureForm() method returns false.
Another option to handle all requests I used in my practice for cases when onload can't help is to handle javascript submit, html submit, ajax requests.
These code should be added in the top of body element to create listener before any form rendered and submitted.
In example I set hidden field to any form on page on its submission even if it happens before page load.
//Handles jquery, dojo, etc. ajax requests
(function (send) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
XMLHttpRequest.prototype.send = function (data) {
if (isNotEmptyString(token) && isNotEmptyString(header)) {
this.setRequestHeader(header, token);
}
send.call(this, data);
};
})(XMLHttpRequest.prototype.send);
//Handles javascript submit
(function (submit) {
HTMLFormElement.prototype.submit = function (data) {
var token = $("meta[name='_csrf']").attr("content");
var paramName = $("meta[name='_csrf_parameterName']").attr("content");
$('<input>').attr({
type: 'hidden',
name: paramName,
value: token
}).appendTo(this);
submit.call(this, data);
};
})(HTMLFormElement.prototype.submit);
//Handles html submit
document.body.addEventListener('submit', function (event) {
var token = $("meta[name='_csrf']").attr("content");
var paramName = $("meta[name='_csrf_parameterName']").attr("content");
$('<input>').attr({
type: 'hidden',
name: paramName,
value: token
}).appendTo(event.target);
}, false);
Use #Kristian Antonsen's answer, or you can use:
$('button').click(function() {
preventDefault();
captureForm();
});

How to Display User Input (composed of a few submissions) in JavaScript?

I can't figure out what exactly am I doing wrong, I only get errors.
index.html
<div id="user-pets">
</div>
<form id="user-pets-form">
<input type="text">
<input type="submit">
</form>
index.js
document.querySelector("#user-pets")
const createPetForm = document.querySelector("#user-pets-form")
createPetForm.addEventListener("submit", (e) => {
e.preventDefault()
let pet = e.target.input.value
document.querySelector("#user-pets").innerHTML += pet
}
After Reviewing your code, you have made two mistakes let me explain,
In JavaScript Code you forgot to add small bracket on second last line,
that's why its through error
In Html you need to add name attribute to Input field, otherwise the listener of submit will always return undefined
I modified both code for you, please have look below
HTML
<div id="user-comments">
</div>
<form id="user-comments-form">
<input type="text" name="comments">
<input type="submit">
</form>
JavaScript
document.addEventListener('DOMContentLoaded', () => {
console.log("DOM is loaded")
document.querySelector("#user-comments")
const createCommentForm = document.querySelector("#user-comments-form")
createCommentForm.addEventListener("submit", (e) => {
e.preventDefault()
let comment = e.target.comments.value;
document.querySelector("#user-comments").innerHTML += comment;
})
})
I suggest you would change the second input to <button type="submit">Submit</button> and add the event listener to it (not the form). Then you can select the value of the input tag, insert it to the comment div when user clicks the submit button

How do I submit data from a text field in HTML to a JavaScript variable?

I cannot figure out how to pass an HTML input to a JS variable.
<form id="form" target="_self">
<input type="text" id="task" placeholder="What's on the agenda?" onsubmit="getForm()">
</form>
My HTML form with the function being called as follows:
function getForm() {
var form = document.getElementById("task").value;
console.log(form);
}
However, when I press enter after typing into the input text, it just refreshes the page and changes the URL from index.html to index.html?task=foo and doesn't log anything in the console.
Try this:
<form id="form" onsubmit="getForm()" target="_self">
<input id="task" placeholder="What's on the agenda?" type="text">
</form>
and
function getForm(event) {
event.preventDefault();
var form = document.getElementById("task").value;
console.log(form);
}
…but keep in mind that you need at least a button or an input to submit the form.
There are two issues with the OP's code.
The getForm function will not execute because onsubmit is wired up against the input element instead of the form element. HTMLInputElement doesn't emit submit events.
The default action of a form is to submit the form to the server, so even if the getForm function were correctly wired up it would execute quickly and then the page would refresh. Likely you want to prevent that default action.
Generally speaking, it's good practice to wire up event listeners in your JavaScript code. Here's a snippet that demonstrates working code akin to what the OP is attempting.
'use strict';
const taskFrm = document.getElementById('taskFrm');
const taskTxt = document.getElementById('taskTxt');
taskFrm.addEventListener('submit', e => {
e.preventDefault();
console.log(taskTxt.value);
});
<form id="taskFrm">
<input id="taskTxt" placeholder="What's on the agenda?">
</form>
For the sake of completeness, if you want to wire up the onsubmit function in the HTML, here's how:
function getForm(e) {
var form = document.getElementById("task").value;
console.log(form);
e.preventDefault(); // Or return false.
}
<form id="form" target="_self" onsubmit="getForm(event)">
<input type="text" id="task" placeholder="What's on the agenda?">
</form>

Clear a field when the user starts filling a form

I have a view with a form in it:
<form asp-controller="UrlP" asp-action="RegisterInput" method="post">
Url: <input asp-for="Url" />
<br />
<button type="submit">Go!</button>
and, on the same view, I have a result from the previous submission:
#if (!string.IsNullOrEmpty(Model.Result))
{
<div class="result">The result is: #Model.Result</div>
}
How can I make the div above (class 'result') disappear as soon a the user starts typing in the form?
To give some context, the app is a single page where you provide a url and you get a result below and I would like to clear the result as soon as a new url is entered.
Since you are using ASP.net Core, it can be handled from the Action and Model State
So after the post, just clear your ModelState and return view like :
ModelState.Clear();
return View(<some View>);
Here's one way.
window.onload = function () {
// attach onkeypress event handler to all text inputs
document.querySelectorAll('form [type=text]').forEach(function (input) {
input.onkeypress = hideResult;
});
};
function hideResult () {
var result = document.querySelector('.result');
// remove result if it exist
if (result) {
result.parentNode.removeChild(result);
}
}
<div class="result">The result is: #Model.Result</div>
<form>
<input type="text" value=""><br>
<input type="text" value="">
</form>

Categories