Reputation: 37
I have written this code, and it works just find, but I feel like I'm being very stupid here and that I could shorten this code. Is there anyway to shorten this? Please leave it as the answer, thank you.
$('.submit-form').on('click' , function() {
if($('.form-signup1').val().length === 0) {
$('.form-signup1').addClass('error')
}
if($('.form-signup2').val().length === 0) {
$('.form-signup2').addClass('error')
}
if($('.form-signup3').val().length === 0) {
$('.form-signup3').addClass('error')
}
if($('.form-signup4').val().length === 0) {
$('.form-signup4').addClass('error')
}
if($('.form-signup5').val().length === 0) {
$('.form-signup5').addClass('error')
}
if($('.form-signup6').val().length === 0) {
$('.form-signup6').addClass('error')
}
});
EDIT: Thank you all so much for your answers, I really do appreciate your time. I chose the one that I could understand best. Thanks again!
Upvotes: 0
Views: 27
Reputation: 15923
If you are validating the value of each input, you could do it like
$('input[type=text]').each(function () {
if ($(this).val().length === 0) {
$this.addClass('error');
}
})
Upvotes: 1
Reputation: 929
$('.submit-form').on('click', function (event) {
event.preventDefault();
var error=0;
$('input[type=text]').each(function () {
var $this = $(this);
error++;
if ($this.val().length === 0) {
$this.addClass('error');
}
});
if(error==0)
$("form")[0].submit();
});
Above code will prevent from submitting while error occurs.
Upvotes: 1
Reputation: 6025
If you can't add a new class to your elements use this
for (var i = 1; i < 7; i++) {
var $this = $('.form-signup' + i);
if ($this.val().length === 0) {
$this.addClass('error');
}
}
Upvotes: 1
Reputation: 388406
Add a common class to all elements then
$('.submit-form').on('click', function () {
$('.form-signup').each(function () {
var $this = $(this);
if ($this.val().length === 0) {
$this.addClass('error');
}
})
});
Upvotes: 1