Radio Button, Text Area and Input check - javascript

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/>";
}
});

Related

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

How to validate empty input boxes from a form in jQuery

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");
}
});
});

javascript form validation with multiple if statements

is this form validation function correct? or it can be done better ?
For example: I want one of the two drop-downs to have a value before checking the contact details fields, (dp1 OR dp2) but even though using ( || ) the validation is acting as &&.
$('#send').click(function(){
if( document.downloadForm.SoftwareDp.value == "0" || document.downloadForm.ManualDp.value == "0" )
{
alert( "Please Select a file for Download" );
return false; }
// First check if Dropdown 1 OR dropdown 2 have been selected ( ONE at least)
if( document.downloadForm.name.value == "" && document.downloadForm.email.value == "" )
{
alert( "Please enter your details" );
return false; }
// then check if name and email are typed in.
else{ // run some ajax if above conditions are met } });
Demo : http://jsbin.com/UGotAFIL/1/edit?html,js,output
Thanks
Your condition working perfectly.
If you want to check both drop down are not selected you should use && instead of ||.
If you need to select at least one drop down means you can you can use
$('#send').click(function(){
if(!( document.downloadForm.SoftwareDp.value != "0" || document.downloadForm.ManualDp.value != "0" ))
{
alert( "Please Select a file for Download" );
return false; }
// First check if Dropdown 1 OR dropdown 2 have been selected ( ONE at least)
if( document.downloadForm.name.value === "" && document.downloadForm.email.value === "" )
{
alert( "Please enter your details" );
return false; }
// then check if name and email are typed in.
else{ // run some ajax if above conditions are met
} });
see this jsbin demo
If I understand you correctly, you want to show the error when no dropdown has a value, that is both have no value.
Change
if( document.downloadForm.SoftwareDp.value == "0" || document.downloadForm.ManualDp.value == "0" )
to either
if( document.downloadForm.SoftwareDp.value == "0" && document.downloadForm.ManualDp.value == "0" ) // both have the default value 0
or
if(!( document.downloadForm.SoftwareDp.value != "0" || document.downloadForm.ManualDp.value != "0" )) // none of them has not the default value
The way you are checking will always give alert unless you select other than 0 values in both.
You should do it this way:
if( document.downloadForm.SoftwareDp.value == "0" && document.downloadForm.ManualDp.value == "0" )
The above will give alert only when both are selected for 0. If one of them has other value it won't display alert.

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"
)
)
)

How can i retrieve a fields name

I have a simple javascript function to check if a field is not empty:
function notEmpty( field , alert_text ){
if (field.val() === "" ||
field.val() === null ||
field.length === 0) {
if ( alert_text ){
alert ( 'Error: please enter some text - ' + alert_text );
} // end if
field.addClass( 'hightlight' );
field.focus();
return false;
} // end if
else {
field.removeClass('hightlight');
return true;
} // end else
I want to get the name of field to show in the alert without using the alert_text argument. I tried a whole load of things, with no luck, so I've left the function as is and I'm using the alert_text argument to pass the field name. All my form input tags are something like this:
<input type= "text"
name= "artist"
id= 'artistfield'
size= "60"
tabindex= "1" />
So they all have 'name' defined. There must be a way to get it into my alert box but I can't figure it out yet. I'm sure it's easy, I'm just very new to this. Thanks.
You can retrieve the name with this:
field_name = field.attr('name');
You can use jQuery's attr() method to get the name (and almost any other HTML attribute):
function notEmpty(field) {
if (field.val() === "" || field.val() === null || field.length === 0) {
if (field.attr('name')) {
alert('Error: please enter some text - ' + field.attr('name'));
}
field.addClass('hightlight');
field.focus();
return false;
} else {
field.removeClass('hightlight');
return true;
}
}
You can use:
field.attr('name')
To get the name attribute from the field. You could change name for id if you wanted the fields ID for example.
To get the name-attribute of an element you can use the attr-function. It can get the value of any attribute.
Eg: http://jsfiddle.net/mqchen/LjFdC/

Categories

Resources