I have a form with 5 fields all with the class 'required'
Im trying to ensure that on submit these fields arent empty, if they are, add a class, if not, return true - ive tried the following only with no luck, even if the fields are empty the form still submits.
$('.submit').click(function(){
if($('.required').val() == "") {
$('.required').addClass('error');
return false;
} else {
return true;
};
});
Try:
$('.submit').click(function(e){
if(!$('.required').val()) {
$('.required').addClass('error');
e.preventDefault();
} else {
return true;
};
});
Try this:
$('.submit').click(function() {
$('.required').removeClass('error').filter(function() {
return !$.trim(this.value).length;
}).addClass('error');
});
Class error is added to empty fields only and is removed otherwise.
http://jsfiddle.net/dfsq/2HxaF/
Another variation which can be useful for your task: additional validation on fields blur:
$('.submit').click(validate);
$(document).on('blur', '.required', function() {
validate($(this));
});
function validate($field) {
($field instanceof jQuery && $field || $('.required')).removeClass('error').filter(function() {
return !$.trim(this.value).length;
}).addClass('error');
}
http://jsfiddle.net/dfsq/2HxaF/1/
if($('.required') will return a collection of jQuery objects, while the call to .val() will only use the first element of that collection to perform your test.
try something like this (EDIT: don't need to do a loop or test, since filter expr will take care of that for you):
$('.submit').click(function(e) {
var ins = $('input.required[value=""]');
ins.addClass('error');
return false;
}
return true;
}
You should use filter to get the empty fields. The form submit is also better to use so that it will handle enter key presses too. If not then you will have to handle the enter key presses inside the form that will trigger the submit event of the form
$('yourform').submit(function(){
// empty will contain all elements that have empty value
var empty = $('.required').filter(function(){
return $.trim(this.value).length === 0;
});
if(empty.length){
empty.addClass('error');
return false;
}
});
A little late to the party but I think this is the best solution:
Replace ALL required fields that weren't filled:
http://jsfiddle.net/LREAh/
$('form').submit(function(){
if(!$('.required').val()) {
$('.required').attr('placeholder', 'You forgot this one');
return false;
} else {
return true;
};
});
Replace only the required field of the submitted form: http://jsfiddle.net/MGf9g/
$('form').submit(function(){
if(!$(this).find('.required').val()) {
$(this).find('.required').attr('placeholder', 'You forgot this one');
return false;
} else {
return true;
}
});
Of course you can change attr('placeholder', 'You forgot this one'); for addClass('error'); -- it was only for demonstration. You don't need the id="formX" on the html btw, I was just trying something else out and forgot to remove.
Related
I'm trying to make an easy validator in jquery for my input fields.
Currently i got the following:
function checkInputs(){
var isValid = true;
$('.input-required').each(function() {
if($(this).val() === ''){
isValid = false;
return false;
}
});
return isValid;
}
And then i got a button right that is this:
$('#confirm').click(function () {
alert(checkInputs());
});
But this always returns true even if the input is empty.
Also after this works am going to make to where if all inputs are filled in, a button will be enabled to click on.
edited it so it has a selector now, still getting always true.
Thanks in advance
Try use the filter attribute to get the inputs that has a required attribute.
$('input').filter('[required]')
Added code to check if inputs are filled and enable or disable button. Note if we use this, there aint much point of the $('#confirm').click(function()); function since this button will only be enabled when the inputs are filled.
function checkInputs() {
var isValid = true;
$('input').filter('[required]').each(function() {
if ($(this).val() === '') {
$('#confirm').prop('disabled', true)
isValid = false;
return false;
}
});
if(isValid) {$('#confirm').prop('disabled', false)}
return isValid;
}
$('#confirm').click(function() {
alert(checkInputs());
});
//Enable or disable button based on if inputs are filled or not
$('input').filter('[required]').on('keyup',function() {
checkInputs()
})
checkInputs()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input required>
<input required>
<input required>
<button id="confirm">check</button>
</form>
Try to target the element in this way:
$('input[required]')
This should do the trick.
if it is 0 then all input filled otherwise it will return 0 mean any one or more are empty input.
function checkInputs(){
var flag = 0;
$('input').each(function() {
if($(this).val() == ''){
return flag = 1;
}
});
return flag;
}
$('#confirm').click(function () {
alert(checkInputs());
});
Your selector is looking for a tagName <input-required></input-required> that obviously doesn't exist.
Add a dot prefix for class
Can also use filter() to simplify
function checkInputs(){
return !$('.input-required').filter(function() {
return !this.value;
}).length;
}
NOTE: Will not work on radios or checkbox if those are part of the collection of elements with that class and you would need to add conditional for type if that is the case
You forgot to put class symbol in jQuery:
function checkInputs() {
var isValid = true;
$('.input-required').each(function() {
if($(this).val() === ''){
isValid = false;
return false;
}
});
return isValid;
}
Try this..
I have a form where I'm using twitter typehead & the problem is whenever twitter typehead loads it creates another input field that is blank ¬ shown to user
Now i have this function to validate all inputs
var fields = $('#second_step input[type=text]');
var error = 0;
if (!$("input[name='career']:checked").val()) {
alert('Please Select yes or no'); return false;
}
fields.each(function(){
var value = $(this).val();
if( value.length<1 || value==field_values[$(this).attr('id')]) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if (!$('#reg').valid()) {
return false;
}
Now due to that typehead input whic has no name or id it just have a certain class tt-hint & this input is read only how can i just skip this input from my above validation?
You can use jQuery's NOT function.
var fields = $('#second_step input[type=text]').not('.tt-hint');
You can filter out the fields with:
var fields = $('#second_step input[type=text]:not(.tt-hint)');
Your input has typeahead applied by using a class selector .typeahead.
So in your case you could use the :not pseudo-class selector to filter them out:
var fields = $('#second_step input[type=text]:not(.typeahead)');
That way you skip the typeahead fields.
Personally I would ignore disabled fields, since the user cannot correct them if there is an error. You say the input is read only so that would seem to correlate.
$('#second_step input[type=text]').filter(function(){ return !this.disabled; })
Try this :
fields.each(function(){
var value = $(this).val();
if($(this).hasClass('tt-hint') {
$(this).addClass('valid');
} else {
if( value.length<1 || value==field_values[$(this).attr('id')]) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
}
});
if (!$('#reg').valid()) {
return false;
}
I have form that has input fields that are required, I point this out with made up class name.
I have piece of code that kind of works. If I focus on required input and then press submit, that input will become red, if empty (which I want). But it only works only on one at a time and if I have focus on the input.
My code is as follows:
function checkIfEmpty(){
$('#register-form input.gv-form-required').blur(function(){
if( !$(this).val()){
$(this).parent().parent().addClass("has-error");
return false;
}else{
return true;
}
});
}
I am almost certain that the blur() method is not suitable for my situation.
So help a man out here, please.
Try this : You have to use .each() to check every input inside form and put removeClass in else condition.
function checkIfEmpty(){
var empty = false;
$('#register-form input.gv-form-required').each(function(){
if($(this).val().trim()==""){
empty = true;
$(this).parent().parent().addClass("has-error");
}else{
$(this).parent().parent().removeClass("has-error");
}
});
return empty;
}
The blur event indeed doesn't seem right in your situation. What I would do is that I would itterate through each field and checked whether it is filled or not. If it is, remove (if any) has-error class. If it isn't filled, give it the has-error class
function checkIfEmpty(){
$('#register-form input.gv-form-required').each(function(){
if($(this).val() === ""){
$(this).parent().parent().addClass("has-error");
}else{
$(this).parent().parent().removeClass("has-error");
}
});
}
change your code to the following:
function checkIfEmpty(){
$('#register-form input.gv-form-required').each(function(){
if( !$(this).is(':empty')){
$(this).parent().parent().addClass("has-error");
}else{
$(this).parent().parent().removeClass("has-error");
}
});
}
try
in else condition
$(this).parent().parent().removeClass("has-error");
js code
if( !$(this).val()){
$(this).parent().parent().addClass("has-error");
}else{
$(this).parent().parent().removeClass("has-error");
}
I need to take text from fields which have the same class. But when I apply the condition that if field is empty, give an alert, it checks the condition for the first time and ignores all the others as fields are all on the same page with the same class. I cannot have unique classes for every field because the divs are dynamically generated.
Here's my code,
$(document).on('click', '.submit-button', function(){
var maintain=$('form input.inputs-field').val ();
if(maintain == ''){
alert('Please fill that field');
return false;
}
else{
$(document).trigger('save-single-answer', {
answer: $(this).siblings('.inputs-field').val()
});
return true;
}
});
Use .each() to check all the fields. Current you just get the value of first matched element in maintain.
$(document).on('click', '.submit-button', function () {
var maintain = $(this).siblings('.inputs-field').val(); //OR $(this).val()
if (maintain == '') {
alert('Please fill that field');
return false;
} else {
$(document).trigger('save-single-answer', {
//here I assume `this` meant button before (in your code)
answer: maintain
});
return true;
}
});
I have this
$("#formNewsletter").submit(function(){
return false;
})
It works as expected - the form is not submited.
When i write this, it seems like it is returning true (the form is being send)
$("#formNewsletter").submit(function(){
if($("#newsletterSelSpec div").length() > 0)
{
alert("Good");
}
else
{
alert("Please add at least one speciality!");
}
return false;
})
I would like to understand why is this happening and how can I make it work.
Thank you!
the property length isn't a method.
Use $("#newsletterSelSpec div").length > 0.
You can prevent the default behavior of an event using preventDefault() witch is a method in the first argument. (event).
$("#formNewsletter").submit(function(event) {
event.preventDefault();
if($("#newsletterSelSpec div").length() > 0)
{
alert("Good");
}
else
{
alert("Please add at least one speciality!");
}
});
Not sure, but the problem can be that the alert stops the process of the script and not the submit event.
$("#formNewsletter").submit(function(e) {
if ($("#newsletterSelSpec div").length > 0) {
alert("Good");
} else {
e.preventDefault(); // prevent the form submission
alert("Please add at least one speciality!");
}
});
NOTE
you're using .length(), but it should be .length only, that means
$("#newsletterSelSpec div").length