How to validate empty input boxes from a form in jQuery - javascript

I would like to validate every single item in my form so in case one is empty I would like to print an alert.
So for that I'm using the form.serializeArray() to check for any input box that could be empty. but my code is not working. Am I doing it good?
Here's my jsfiddle code

instead of var form = page.find(..);
use var form = $(..);
modified..
http://jsfiddle.net/vqr22ebz/6/
But there is another problem, you are calling the alert for every empty field.

The .find() method searches for a specified text in the document and highlights the matches.
You can further simplify your code:
$( "#myform" ).submit(function( form ) {
$(this).serializeArray().forEach(function (i, v) {
if (v.value == '' || v.value == null || typeof v.value == 'undefined') {
alert("need to fill up all those fields");
}
});
});

You are calling page.find() instead of $('') for selecting your form.
Suggestion 1 :
To improve your code and don't repeat code uselessly you can change your code like that :
$("#myform").submit(function() {
var formItems = $(this).serializeArray();
formItems.forEach(function (i, v) {
if (v.value == '' || v.value == null || typeof v.value == 'undefined') {
window.alert("need to fill up all those fields");
}
});
});
Suggestion 2 :
To not make too many pop-up; you can specify the field who is empty.
$("#myform").submit(function() {
var formItems = $(this).serializeArray();
formItems.forEach(function (i, v) {
if (v.value == '' || v.value == null || typeof v.value == 'undefined') {
$('input[name="' + v.name + '"]').val("This field must not be empty");
}
});
});

Related

Selector to check selected value of all drop down lists

I'm trying to find a way to check wether the value selected of all my drop down lists !='' using just one selector in JQuery.
Instead of :
if ($("#list1").val() != '' && $("#list2").val() != ''
&& $('#list3').val() != '' && $('#list4').val() != '') {
//do stuff
}
Is it possible ?
You can add a class to those elements and code:
var vals = $('select.lists').map(function() {
return this.value;
}).get().join('');
if ( vals != '' ) {
// ...
}

Check value of both text boxes if they have values in it or not

My page have multiple textboxes i wanted to make sure if user select value from text box 1 and leaves text box 2 empty then it should alert a popup that you must have to enter values in both textboxes.
i do not want to compare values with each other.(Like both textbox value must be same)
Textbox 1 is Number field and text box 2 is date field.
If any one value is entered then it should not allow user to submit page it should stop processing and redirect to that textbox which is empty.
Now what i have tried so far.
$( "#button_id" ).click(function() {
var n = document.getElementById('text1');
var m = document.getElementById('text2');
if(n.value.trim() != "" || n.value == undefined)
{
if (n.value.trim() != "" && m.value.trim() == "")
{
alert("text1 should have some value");
return false;
}
}
if(m.value.trim() != "" || m.value == undefined)
{
if (m.value.trim() != "" && n.value.trim() == "")
{
alert("text2 should have some values");
return false;
}
}
});
As mention below code i just wanted to check if textbox is disable or not if textbox is disable then do not test for validation else do.
Partial Solution :
var _domArray = [$("#textbox1"),$("#textbox2")]
var chk = $x('textbox2').disabled = false;
$( "buttonid" ).click(function() {
_domArray.forEach(function(item){
if(item.val() ==''){
var _getId =item.attr('id');
alert(_getId +" should have some value" );
this.browserEvent.preventDefault();
this.browserEvent.stopImmediatePropagation();
return false;
}
})
});
Use the required attribute on your <input>s, then you can check in JavaScript with document.querySelector('form.insertSelectorHere').matches(':valid').
Use an array to store the DOM element,Loop through it and check to check if it is empty, If so through an alert.
Also assuming you are using input type number & date
var _domArray = [$("#text1"),$("#text2")]
$( "#button_id" ).click(function() {
_domArray.forEach(function(item){
if(item.val() ==''){
var _getId =item.attr('id');
alert(_getId +" should have some value" )
}
})
});
Using jquery since you have tagged this with jquery
jsfiddle

Radio Button, Text Area and Input check

I have a form with all the input fields as class item. When I click submit, it checks, with the following function if all values are filled in.
$.each($(".items"),function(i,e){
// loop through all the items
if(e.value == "" || !$("input[name='"+e.name+"']:radio:checked").length)
if(error.indexOf(e.title) === -1)
error += e.title + "<br/>";
});
This form comprises of text areas, radio boxes and normal text input fields. It returns all the radio boxes not filled in, as well as all the text inputs not filled in. But then it also returns ALL the text areas, regardless of whether it's filled in or not.
I first thought it was because I specified it to check the value, but it seems the value check does in fact check text areas, so it can't be that.
Could anyone assist me in making it return only empty elements?
$.each( $( '.items' ), function() {
if ( ( this.type === 'checkbox' || this.type === 'radio' ) && !this.checked ) {
// Go
}
else if ( this.value === '' ) {
// Do your stuff
}
});
Unfortunately, it seems there is no other choice but to separate the cases.
$.each($('.items'),function(i,elem){
if( ($(elem).attr('type') == 'radio' || $(elem).attr('type') == 'checkbox') && !$(elem).is(':checked') ) {
// RADIOS AND CHECKBOXES EMPTY
} else if( $(elem).val().length == 0 ) {
// INPUTS TYPE TEXT AND TEXTAREA EMPTY
}
});
So I used a combination of JBRTRND and Florian Margaine's answers as neither wanted to work 100% correctly.
I just put this here incase someone is stuck on the same issue. I in no way take credit for ANY of the help I received from them and I'm really thankful for it.
This is how I fixed it:
$.each($(".items"),function(){
// loop through all the items
// and alert the value
if ( this.type == 'radio' && !$("input[name='"+this.name+"']:radio:checked").length) {
if(error.indexOf(this.title) === -1)
error += this.title + "<br/>";
}
else if ( this.value === '' ) {
if(error.indexOf(this.title) === -1)
error += this.title + "<br/>";
}
});

Adding an if statement inside if statement

I have a function for a button which submits a form. This function checks to see if the 5 checkboxes are selected #co1,#co2,#co3,#div1,#cc1.
It then also checks to see if tcaccept select is set to 1.
If so the form submits, else the alert pops up.
This is the code i have at the moment:
$('#submit2pd').click(function(event) {
var $finishBoxes = $('#co1,#co2,#co3,#div1,#cc1');
if (!($finishBoxes.length == $finishBoxes.filter(':checked').length && $('#tcaccept').val() == '1' )) {
alert('Please complete the Induction Checklist confirming that you have read and understood the Colleges main policies and procedures, agreeing to comply with these in line with the terms of your contract with the College');
return false;
}
// otherwise the form is submitted
window.location.href = "submit2pd.php";
});
All works brilliantly, but i want to add to this line as i have another option that is required. But this needs to be an if statement.
if (!($finishBoxes.length == $finishBoxes.filter(':checked').length && $('#tcaccept').val() == '1' && THE IF STATEMENT))
this is what i need to incorporate into the if statement above.
if ($("#ctl").val() == "1") {
$('#ctlapp') must not be blank
}
else if ($("#ctl").val() == "0") {
$('#ctlapp') can be blank
}
Any help would be greatly appreciated.
How about:
if (!($finishBoxes.length == $finishBoxes.filter(':checked').length &&
$('#tcaccept').val() == '1' &&
!($("#ctl").val() == "1" && $('#ctlapp').val() === "")))
What we're adding here is another condition which says, "And make sure it's not the case that #ctl is 1, and #ctlapp is blank".
Edit: and please see my comment above - your question is not about jQuery, forms, or validation. It's barely about JS.
if($('#tcaccept').val() == '1' && validate()) {
// do something
}
var validate = function(){
if ($("#ctl").val() == "1") {
$('#ctlapp') must not be blank
return false;
}
else if ($("#ctl").val() == "0") {
$('#ctlapp') can be blank;
return true;
}
return true;
}
I'd say clean up the code a little, and things will get a bit simpler:
$('#submit2pd').click(function(event) {
var fail_message = 'Please complete the Induction Checklist confirming that you have read and understood the Colleges main policies and procedures, agreeing to comply with these in line with the terms of your contract with the College',
$finishBoxes = $('#co1,#co2,#co3,#div1,#cc1'),
$checkedBoxes = $finishBoxes.filter(':checked'),
tcaccept = $('#tcaccept').val(),
ctl = $("#ctl").val(),
ctlapp = $('#ctlapp').val();
if (tcaccept == '1' && $finishBoxes.length != $checkedBoxes.length ) {
alert( fail_message );
return false;
} else if( ctl == "1" && ctlapp == "" ) {
alert( "some other message" );
return false;
}
// otherwise the form is submitted
window.location.href = "submit2pd.php";
});
I left the test for $('#ctl').val() == "0" out because it sounds like that's the only other value it can have, and there's no validation that needs to take place if it is "0".
Use a logic or || to capture both constalations:
$("#ctl").val() == "1" && $('#ctlapp') != ""
OR
$("#ctl").val() == "0"
if (
!(
$finishBoxes.length == $finishBoxes.filter(':checked').length
&&
$('#tcaccept').val() == '1'
&&
(
($("#ctl").val() == "1" && $('#ctlapp') != "")
||
$("#ctl").val() == "0"
)
)
)

More efficient way of writing this javascript

I am creating a contact form for my website and and using javascript to the first layer of validation before submitting it which is then checked again via php but i am relatively new to javascript, here is my script...
$("#send").click(function() {
var fullname = $("input#fullname").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
if (fullname == ""){
$("input#fullname").css("background","#d02624");
$("input#fullname").css("color","#121212");
}else{
$("input#fullname").css("background","#121212");
$("input#fullname").css("color","#5c5c5c");
}
if (email == ""){
$("input#email").css("background","#d02624");
$("input#email").css("color","#121212");
}else{
$("input#email").css("background","#121212");
$("input#email").css("color","#5c5c5c");
}
if (subject == ""){
$("input#subject").css("background","#d02624");
$("input#subject").css("color","#121212");
}else{
$("input#subject").css("background","#121212");
$("input#subject").css("color","#5c5c5c");
}
if (message == ""){
$("textarea#message").css("background","#d02624");
$("textarea#message").css("color","#121212");
}else{
$("textarea#message").css("background","#121212");
$("textarea#message").css("color","#5c5c5c");
}
if (name && email && subject && message != ""){
alert("YAY");
}
});
How can i write this more efficiently and make the alert show if all the fields are filled out, thanks.
$("#send").click(function() {
var failed = false;
$('input#fullname, input#email, input#subject, textarea#message').each(function() {
var item = $(this);
if (item.val()) {
item.css("background","#121212").css("color","#5c5c5c");
} else {
item.css("background","#d02624").css("color","#121212");
failed = true;
}
});
if (failed){
alert("YAY");
}
});
glavic and matt's answers were exactly what I was going to suggest, except I would take it a step further by separating the logic from the presentation.
Have classes defined in your css for when a field contains an invalid entry, and add or remove that class using $.addClass() or $.removeClass()
Since you're using jQuery, I would recommend setting a class on each field that requires a non-blank value (class="required").
Then you do something like this:
var foundEmpty = false;
$(".required").each(function()
{
if($(this).val())
{
foundEmpty=true;
$(this).style("background-color", "red");
}
});
if(foundEmpty)
{
alert("One or more fields require a value.");
}
Giving them a common class, define classes to apply the styles, and do this:
JS
$("#send").click(function() {
$('.validate').attr("class", function() {
return $(this).val() === "" ? "validate invalid" : "validate valid";
});
if( $('.invalid').length === 0 ) {
alert('YAY');
}
});
CSS
.valid {
background:#121212;
color:#5c5c5c
}
.invalid {
background:#d02624;
color:#121212;
}
HTML
<button id="send">SEND</button><br>
<input class="validate"><br>
<input class="validate"><br>
<input class="validate"><br>
<input class="validate">
JSFIDDLE DEMO
A little bit more efficient approach:
var validate = $('.validate');
$("#send").click(function() {
validate.attr("class", function() {
return $(this).val() === "" ? "validate invalid" : "validate valid";
});
if( validate.filter('.invalid').length === 0 ) {
alert('YAY');
}
});
You can use jQuery to iterate over each object and get their values. Depending on your form, this code will change, but it's to give you an example. I'm probably missing a couple of brackets here and there but the concept is there.
var objectName=$(this).attr('id');
$('#formId').children().each(
function(){
if ($(this).value == ""){
$(this).css("background","#d02624");
$(this).css("color","#121212");
$error[objectName]='true';
}else{
$(this).css("background","#121212");
$(this).css("color","#5c5c5c");
$error[objectName]='false';
}
}
);
$.each(error, function(key, value){
if (value=='false'){
alert (key + 'is empty');
}
});
I would probably divide part of this up into my css file. If any of the fields are empty add a class like "empty" to the object, if not, remove it. Then in your css file you can add some descriptors like:
input#fullname,
input#email {
...
}
input#fullname.empty,
input#email.empty {
...
}
You can use jQuery addClass() and removeClass().
You can then add a loop as follows:
var inputs = new Array();
inputs[0] = "input#fullname";
inputs[1] = "input#email";
inputs[2] = "input#subject";
inputs[3] = "textarea#message";
var complete = true;
for (var i = 0; i < 4; i++) {
var value = $(inputs[0]).val();
if (value.length > 0) {
$(inputs[i]).removeClass("empty");
} else {
complete = false;
$(inputs[i]).addClass("empty");
}
}
if (complete) {
}
EDIT:
There you go, fixed it for you.

Categories

Resources