I ran into a situation where I have a HTML form and it has required on many of the fields. The issue is I have to use preventDefault which ignores 'required' inputs and submits the form even without the required fields. Because the work is not entirely up to me I must use preventDefault and work around it.
I am working with jQuery and I am trying to find a way to target the fields that have required and prevent the form from submitting on click.It is important that the required fields are filled out on the form before a user can submit the form as I do not want required information missing when it is being submitted. Help is appreciated!
HTML
<form id="myForm">
<input type="text" name="sentence1" id="st1" placeholder="Text here" required>
<input type="text" name="sentence1" id="st2" placeholder="Text here" required>
<input type="text" name="sentence1" id="st3" placeholder="Text here" required>
<input type="text" name="sentence1" id="st4" placeholder="Text here" required>
<input type="text" name="sentence1" id="st5" placeholder="This field is not required">
<button type="submit" id="submit-form">Submit</button>
</form>
Came across the same problem and here is the solution that works for me.
Form elements have a function called checkValidity and reportValidity. We can use these and override the click event for the submit button.
$('#submit-form').click((event) => {
let isFormValid = $('#myForm').checkValidity();
if(!isFormValid) {
$('#myForm').reportValidity();
} else {
event.preventDefault();
... do something ...
}
});
In your event handler, where you are using preventDefault(), add the checkValidity() method on the form element:
document.getElementById('myForm').checkValidity();
This will "statically" check your form for all HTML5 constraint violations (including required),
Just a quick solution for your problem. I hope this is what you need. Check below:
$('#submit-form').click(function(){
event.preventDefault();
if(validateForm()){
alert('sending');
}
});
function validateForm() {
var isValid = true;
$('input[type=text]').each(function() {
if ( $(this).val() === '' ) {
alert('validation failed');
isValid = false;
}
});
return isValid;
}
Or visit JSFiddle: enter link description here
You can use preventDefault() in forms submit method. Then 'required' will work.
document.querySelector('form').addEventListener('submit', submitHandler);
function submitHandler(e){
e.preventDefault();
//your code here
}
Related
I'd like to display a message above the name field if the user submits a name with a length greater than 20. This means the form will not get submitted - in other words, the form's action won't be triggered.
I've tried almost every suggestion I could find to prevent the form action from being triggered upon form validation but nothing seems to be working.
I've hit a wall with this and can't figure out what I'm doing wrong. How can rectify this?
html:
<form method="POST" id="form" action="/post.php">
<span class="nameError"></span>
<input type="text" class="name" name="name" placeholder="Name" required/>
<input class="button" type="submit" value="Submit"/>
</form>
Here's my jquery:
let name = $('.name');
let nameError= $('.nameError');
$(document).ready(function() {
$('input[type=submit]').on('click', function(e) {
if (name.length > 20) {
e.preventDefault();
nameError.val("Too many characters!");
return false;
}
});
});
I have modified the logic for validation. Basically we need to capture the submit event for the form and use the correct jquery methods to retreive data based upon the selectors.
$(document).ready(function() {
$("#form").submit(function( event ) {
let name = $('.name').val();
let nameError= $('.nameError');
if (name.length > 20) {
nameError.text("Too many characters!");
event.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<form method="POST" id="form" action="/post.php">
<input type="text" class="name" name="name" placeholder="Name" required/>
<label class="nameError"></label> <br/>
<input class="button" type="submit" value="Submit"/>
</form>
I have a line
document.getElementById("firstName").addEventListener("blur", validateField);
and :
validateField = (event) =>
{
const el = event.target;
}
Now I want to call the validateField() function with the respective element in the form.addEventListener('submit', function(event) line.
document.getElementById("firstName").blur(); // This is not getting called.
But cold-calling blur() isn't working.
What I am trying to do is to populate the bootstrap is-invalid message when the form is called and still invalid.
el.classList.add('is-invalid');
el.nextElementSibling.innerHTML = "This field is required";
Trying to avoid jQuery as I may switch this over to bootstrap version 5.
I do think technically, submitting form unfocuses, unless the user presses the enter key to submit. An alternate approach is maybe, you can try to focus on something else than blurring a particular thing!
The following code works for me.
document.getElementById("frm").addEventListener('submit', function(event) {
event.preventDefault();
document.getElementById("firstName").blur();
});
<form action="" id="frm">
<input type="text" id="firstName" />
<input type="submit" value="Press Enter" />
</form>
But for the alternate solution:
document.getElementById("frm").addEventListener('submit', function(event) {
event.preventDefault();
document.getElementById("frm").focus();
});
#frm:focus {
outline: none;
box-shadow: none;
}
<form action="" id="frm" tabindex="0">
<input type="text" id="firstName" />
<input type="submit" value="Press Enter" />
</form>
I need each instance of input and submit to operate independently. What is the best way to handle multiple instances where each submit is connected to it's own set of inputs?
Since they are unrelated, would data-attributes be the best solution?
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item1">
<div><input type="text" name="name" autocomplete="off" required/></div>
<input type="submit" value="Submit 1" />
</div>
<div class="item2">
<div><input type="text" name="name" autocomplete="off" required/></div>
<div><input type="text" name="name" autocomplete="off" required/></div>
<input type="submit" value="Submit 2" />
</div>
I think your intuition about using data attributes works great here.
var allButtons = document.querySelectorAll("input[type=submit]");
allButtons.forEach(button => {
button.addEventListener("click", () => {
var inputSet = button.getAttribute("data-input-set");
var inputs = document.querySelectorAll("input[type='text'][data-input-set='" + inputSet + "']");
});
});
In the following code, when an input button is pressed, it will fetch all the inputs with the corresponding "input-set" tag.
Preferred way
I think best solution would be use form -tag as it is created for just this use case HTML Forms.
<form id="form-1">
<input type="text"/>
<input type="submit>
</form>
<form id="form-2">
<input type="text"/>
<input type="submit>
</form>
You can also bind custom Form on submit event handlers and collect form data this way.
$('#form-1').on('submit', function(event){
event.preventDefault(); // Prevent sending form as defaulted by browser
/* Do something with form */
});
Possible but more bolt on method
Alternative methods to this would be to create your own function's for collecting all relevant data from inputs and merge some resonable data object.
I would most likely do this with giving desired class -attribute all inputs I would like to collect at once eg. <input type="text" class="submit-1" /> and so on. Get all elements with given class, loop through all them and save values into object.
This requires much more work tho and form -tag gives you some nice validation out of the box which you this way have to do yourself.
I'm trying to check if the textbox is empty for my form. However, whenever I try to hit submit instead of an alert box message, telling me Firstname is empty I get "Please fill out filled".
('#submit').click(function() {
if ($('#firstname').val() == '') {
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" required placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Firstly I'm assuming that the missing $ is just a typo in the question, as you state that you see the validation message appear.
The reason you're seeing the 'Please fill out this field' notification is because you've used the required attribute on the field. If you want to validate the form manually then remove that attribute. You will also need to hook to the submit event of the form, not the click of the button and prevent the form submission if the validation fails, something like this:
$('#elem').submit(function(e) {
if ($('#firstname').val().trim() == '') {
e.preventDefault();
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Personally I'd suggest you use the required attribute as it saves all of the above needless JS code - unless you need more complex logic than just checking all required fields have been given values.
Because you have the required property set.It is giving you Please fill out field validation as the error message.It is the validation that HTML5 is performing.
For this please make one function like :
function Checktext()
{
if ($('#firstname').val() == '') {
alert('Firstname is empty');
return false;
}
else
{
return true;
}
}
now call this function on submit button click like :
<input type="submit" id="submit" value="Submit" onclick="return check();" />
Have a basic registration form, trying to validate it.
I am using form serializeArray() method and loop trough the form and find if the values are null.
HTML CODE
<form name="reg" id="regform">
<fieldset>
<label for="firstname">First Name</label>
<input type="text" name="firstname" value="First Name"/>
</fieldset>
<fieldset>
<label for="lastname">Last name</label>
<input type="text" name="lastname" value="Last Name"/>
</fieldset>
<fieldset>
<label for="date">Age</label>
<input type="text" name="age"/>
</fieldset>
</form>
JQUERY Code
var formElements = $("#regform").serializeArray();
$(formElements).each(function(x)
{
if(formElements[x]["value"] == "")
{
$("[name='" + formElements[x]['name'] +"']").addClass('error');
}
});
From the above code i am able to add the class ".error" when the value is null.
Now i want the code to check the text fields values are not the default values like in my case the default values are "First Name" "Last Name"..
So i want to check even for the default values and add error class to respective element and even focus back the cursor on the first null value text field
Thanks in advance
I highly suggest using http://docs.jquery.com/Plugins/Validation. You can test for various things, such as blank values, and even extend it to detect default values.
For example:
$.validator.addMethod("name", function(value) {
return value != "First Name";
}, 'Please enter your first name.');
Alternatively you can just test against a default value with jQuery's data() function:
Working Demo: http://jsfiddle.net/WpQ2n/2/
var input = $(".name"),
defaultval = input.data("default", input.val());
// Can't submit forms in jsfid, so i just used a click event.
// Change to .submit()
$("input[type='submit']").on("click",function(e){
if(input.val()== input.data("default")){
input.addClass("error");
}
else{
// Yay it validated...
input.removeClass("error");
}
e.preventDefault();
});