Conditional jQuery validation based on custom attribute - javascript

I'd like to enable/disable buttons on key up change conditionally based on a custom data attribute that matches between an input and a button. I've solved it with just one input, but it seems that when I add another one in the mix, the buttons don't seem to enable.
Furthermore, I have a hunch that it's because of .each() but I can't put my finger on it.
Here's the CodePen I've tried and failed on
var validation = $('[data-validation]');
var validate;
validation.on("change keyup", function (e) {
let validated = true;
validation.each(function () {
let value = this.value;
validate = $(this).data('validation');
if (value && value.trim() != "") {
validated = false;
} else {
validated = true;
return false;
}
});
if (validated) {
$('[data-validator=' + validate + ']').prop("disabled", true);
} else {
$('[data-validator=' + validate + ']').prop("disabled", false);
}
});

The key here is to only run your validation code for the input that was changed. As opposed to what you have, which is to run for all inputs.
To get the input that actually changed, you can utilize the .target property of the event object passed to the event handler.
Alternatively, if you remove the validation.each() entirely, it also works. That is because jQuery sets the value of this to be the DOM element (not a jQuery-wrapped element) that actually triggered the event.
var validation = $("[data-validation]");
var validate;
validation.on("change keyup", function (e) {
let validated = true;
let value = this.value;
validate = $(this).data("validation");
if (value && value.trim() != "") {
validated = false;
} else {
validated = true;
return false;
}
if (validated) {
$("[data-validator=" + validate + "]").prop("disabled", true);
} else {
$("[data-validator=" + validate + "]").prop("disabled", false);
}
});

Related

How to preventDefault from external function and not in the event Listener?

I have this event listener, to submit a form.
document.getElementById("form").addEventListener("submit", (e) => {
const inputs = document.querySelectorAll('#form input');
// Check for empty fields
if ([...inputs].some(input => !input.value)) {
e.preventDefault(); // Prevent form submitted until all fields are not empty
}
for (var i = 0; i < inputs.length; i++) {
// Validate specific inputs - where "name" starts with "actual-temp"
if(inputs[i].name.startsWith("actual-temp")) {
validateActualTemp(inputs[i].value, inputs[i]); // This is another function to check values
}
}
});
And after this event Listener I have this function:
function validateActualTemp(value, item) {
if(value === '10') {
item.style.backgroundColor = 'red';
console.log(item);
}
}
This validates input fields - and checks if the number is shown. What I need to do now is, if the value === '10' then stop submitting the form, even if the fields are all filled out.
I have tried this:
function validateActualTemp(value, item) {
if(value === '10') {
preventDefault();
item.style.backgroundColor = 'red';
console.log(item);
}
}
But it is not working - How can I preventDefault(); in an external function?
Simply pass the event to the other function:
//...
validateActualTemp(inputs[i].value,inputs[i],e)
//...
function validateActualTemp(value, item,e) {
if(value === '10') {
e.preventDefault();
item.style.backgroundColor = 'red';
console.log(item);
}
}
Or return true/false from your validation function and handle everything else in the event handler callback.

jQuery - Validation

I'm having an issue with my validation process. I'm not using a standard "submit" button, rather I have <span class="button" id="print">Print</span> and jQuery listens for a click. This is the validation code I have when that "button" is clicked:
var validation = "";
function validate() {
$("#servDetails").find("input").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
$("#checklist").find("input[required]").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
}
$("#print").on("click", function() {
validate();
if (validation == false) {
alert("Please fill out all required inputs!");
return false;
}
else {
window.print();
}
});
If I click the button without filling anything out (all items blank), I get my alert as expected.
If I fill out all of the required elements, it pulls up the print dialouge as expected.
However, if I leave some of the boxes blank while others are correctly filled, it still goes to print instead of giving me the alert like I need. Any thoughts?
The code have to be rewritten, or better replace it with any validation plug-in.
But in your case, I suppose, you just forgot to return, in case you found some not filled field. So if you have any filled input it override your validation variable.
The simplest solution is to remove
else {validation = true;} code blocks, and add
validation = true;
at the beggining of the function.

Keypress in text input preventing typing

I have a text input that I want to execute a function when enter is pressed. I used if condition to determine if enter is pressed but this causes the user not to be able to type in the input box. What can I put in the else condition to allow them to type normally?
JsFiddle
function addItem(e) {
e.preventDefault(); // Prevent form being submitted
var text = $('input:text').val(); // Get value of text input
var itemArr = text.split(',');
var lngth = itemArr.length
for(i = 0; i < lngth; i++)
{
$list.append('<li>' + itemArr[i] + '</li>'); // Add item to end of the list
updateCount(); // Update the count
} // End loop
$('#addItems').val(''); // Empty the text input
return false;
}
$('#addItems').keypress(function(e) {
if(e.which == 13) {
addItem();
}
return false;
});
Remove return false; from the keypress function.
$('#addItems').keypress(function(e) {
if(e.which == 13) {
addItem();
}
else {
return true;
}
return false;
});
Jusr remove return false from the keypress event
You can see this Question
return false; successfully cancels an event across browsers if called at the end of an event handler attribute in the HTML.
and to prevent form from form being submitted, you can add onsubmit="return false" to the form
Demo

Wait for the return of the loop on form submit

I have the code below, the form is needed to be validated before it can submit the form.
But the problem is, the form continues to submit without validating.
<form action='#' method='post' onsubmit='return validate();'>
function validate()
{
$('form').find(':input:not(:submit,:hidden), select, textarea').each(function(e)
{
$(this).removeClass('redBox');
var rq = $(this).attr('requiredz');
if(rq != undefined)
{
if($(this).val().trim() == '')
{
$(this).addClass('redBox');
$("#errorMsg").html('Red boxes cannont be left empty!');
return false;
}
}
});
});
How to handle the return of a loop?
Dont submit the form once encountered return false on the loop.
try this:
function validate()
{
var passes = true;
$('form').find(':input:not(:submit,:hidden), select, textarea').each(function(e)
{
$(this).removeClass('redBox');
var rq = $(this).attr('requiredz');
if(rq != undefined)
{
if($(this).val().trim() == '')
{
$(this).addClass('redBox');
$("#errorMsg").html('Red boxes cannont be left empty!');
passes = false;
}
}
});
return passes;
});
Do not use return.
$('#my-form').on('submit', function(event){
if (validate() === false) {
event.preventDefault(); // like return false;
}
});
For more information see jQuery submit docs.
Each function has it's own returned value, the default returned value is an undefined value. You should check the length of the invalid elements after the each loop and return a proper value, since you are using jQuery I'd suggest:
$('form').on('submit', function (event)
{
var $invalid = $(this)
.find(':input:not(:submit,:hidden), select, textarea')
.removeClass('redBox')
.addClass(function () {
return this.getAttribute('requiredz')
&& $.trim(this.value) === ''
? 'redBox'
: null;
}).filter('.redBox');
if ($invalid.length)
{
$("#errorMsg").html('Red boxes cannont be left empty!');
return false;
}
});

Re-enabling Submit after prevent default

I am trying to unbind or reenable the prevent default so my form will submit on good data.
I have tried multiple examples. Here is my code and some of the examples i tried.
This code works great for what i want to. Just the last thing and resetting the div which i can implement after i get this.
function lengthRestriction(elem, min, max) {
var uInput = elem.value;
if (uInput.length >= min && uInput.length <= max) {
return true;
} else {
var cnt = document.getElementById('field');
cnt.innerHTML = "Please enter between " + min + " and " + max + " characters";
elem.focus();
$('#ShoutTweet').submit(function(e) {
e.preventDefault();
//bind('#ShoutTweet').submit();
//$('#ShoutTweet').trigger('submit');
});
}
}​
i have a jsbin set up too http://jsbin.com/ebedab/93
Don't try to set up and cancel a submit handler from within your validation function, do it the other way around: call the validation from within a single submit handler, and only call .preventDefault() if the validation fails:
$(document).ready(function() {
$('#ShoutTweet').submit(function(e) {
if (/* do validations here, and if any of them fail... */) {
e.preventDefault();
}
});
});
If all of your validations pass just don't call e.preventDefault() and the submit event will then happen by default.
Alternatively you can return false from your submit handler to prevent the default:
$('#ShoutTweet').submit(function(e) {
if (!someValidation())
return false;
if (!secondValidation())
return false;
if (someTestVariable != "somevalue")
return false;
// etc.
});
I'm not completely sure what you are asking, but if your goal is to destroy your custom submit handler, then use this:
$("#ShoutTweet").unbind("submit");
This assumes that you have a normal (not Ajax) form.
Just call submit on the form
$('#ShoutTweet').submit();
This works surely and enable form submission after event.preventDefault();
$('#your-login-form-id').on('submit', onSubmitLoader);
function onSubmitLoader(e) {
e.preventDefault();
var self = $(this);
setTimeout(function () {
self.unbind('submit').submit(); // like if wants to enable form after 1s
}, 1000)
}

Categories