I have a form myForm and I want to check if specific input field are filled out before sending the form. I'm very new to JavaScript so I don't really know what I did wrong. Any help is welcomed.
function validateForm() {
var validate = true;
var alert_string = "";
var children = $("#myForm").children("input");
console.log(children.size());
for(var i = 0; i < children.length ; i++){
if(children[i].attr(id).substring(0,8) != "ABC_FLAT"){
if(children[i].attr(id) == null || children[i].attr(id) == ""){
validate = false;
alert_string = alert_string.concat(childrern[i].attr(id)).concat(", ");
}
}
}
alert_string = alert_string.concat("must be filled out !");
if(validate == false){
alert(alert_string);
return false;
}
return true;
}
children[i].attr(id) == "" // wrong
You don't have to check whether their ids are null, you have to check whether their values are empty :)
if(children[i].value == "")
Since you are already using jQuery, you can simplify that code to a great extent. For example a simple "all fields filled" check can be
var flag=0;
$('#myForm').each(function() {
if ( $(this).val() === '' )
flag=1;
});
if you'll use jQuery, you can check the input fields if empty AND trap also white space/s. Add a class to all input fields , e.g. class="required" and add attribute fieldname with respective value for each input field.
var requiredFields = "";
$("#myForm").find('.required').each(function () {
if ($(this).val().trim().length == 0) {
requiredFields += " - " + $(this).attr("fieldname") + "\n";
}
});
if (requiredFields != "") {
alert("Please enter the following required field(s): \n" + requiredFields);
} else {
//save here
}
You can use required like <input required type="text" name="email" id="log" /> or use jQuery like
$("form").submit(function() {
var has_empty = false;
$(this).find('input').each(function() {
if(! $(this).val()) {
has_empty = true;
return false;
}
});
if(has_empty){return false;}
});
Related
In the given code i have create a dynamic textarea, now when i try to get insert value from that textarea. It gives me null value.
<form name="myForm">
<textarea name="fname" <%#!((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).Code.Equals("OTH", StringComparison.InvariantCultureIgnoreCase) ? "style='display: none;'" : string.Empty%> id="text<%#((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).ID%>" maxlength="50" placeholder="Enter other item details"></textarea>
</form>
Given is my function to get value from textarea box:
function ValidateData() {
if ($("textarea").is(":visible")) {
//var x = document.forms["myForm"]["fname"].value;
var x = document.getElementsByName("fname").value;
if (x == null || x == "") {
alert("Please Enter Other Item Details");
return false;
}
}
else return true
}
Your textarea was dynamic so you can used textarea change event. You can use given code on load, so whenever you input text it sets on OtherItemValue:
var OtherItemValue;
$("textarea").on('input change keyup', function () {
if (this.value.length) {
OtherItemValue = this.value;
} else {
OtherItemValue = "";
}
});
And then you can used below code:
function ValidateData() {
if ($("textarea").is(":visible")) {
if (OtherItemValue == null || OtherItemValue == "") {
alert("Please Enter Other Item Details");
return false;
}
}
else return true
}
Since you are using jQuery already, why don't you use it to achieve the desired result?
Your code would look like this:
function ValidateData() {
if ($("textarea").is(":visible")) {
var x = $("textarea").val();
if (x == null || x == "") {
alert("Please Enter Other Item Details");
return false;
}
}
return true
}
If you really need to use standard library, #Rachit Gupta's answer should solve the problem.
<form name="myForm">
<textarea name="fname" <%#!((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).Code.Equals("OTH", StringComparison.InvariantCultureIgnoreCase) ? "style='display: none;'" : string.Empty%> id="text<%#((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).ID%>" maxlength="50" placeholder="Enter other item details"></textarea>
</form>
Your function should now look like this
function ValidateData() {
if ($("textarea").is(":visible")) {
//var x = document.forms["myForm"]["fname"].value;
var x = document.getElementsByName("fname")[0].value;
if (x == null || x == "") {
alert("Please Enter Other Item Details");
return false;
}
}
else return true
}
The problem with your code is that getElementsByName will get a list of elements, which don't have a value property. You need to get only a particular element and get its value. This solution may solve your problem, but will work if you don't have any other element with name as fname above the textarea.
Use jquery .val() method to retrieve the value of the text area.
you need to initialise textarea to empty at document ready function.
$(document).ready(function(){
$("textarea[name='fname']").val("");
});
function ValidateData() {
if ($("textarea").is(":visible")) {
var x = $("textarea[name='fname']").val();
if (x == null || x == "") {
alert("In if " + x);
return false;
}
else {
alert("In else" + x);
}
}
else {
return true
}
}
I have 2 address entries on my form. I also have 2 radio buttons to designate the "preferred" mailing address.
I'm attempting to validate these 2 and am not really sure if I'm doing it correctly. It seems to work if I have both addresses filled but I can't seem to get it to validate correctly if one of the addresses isn't filled.
Here's the javascript that does the validation:
function checkMailingPrefs() {
var prefs = ["MailPrefHome", "MailPrefBusi"];
var field = ["HomeAddress1", "BusinessAddress1"];
for (i = 0; i < 2; i++) {
if ($("#"+prefs[i]).is(":checked") && $("#"+field[i]).val() == "") {
$("#" + prefs[i]).prop('checked', false);
$("#MailPrefBusi").validationEngine('showPrompt', 'You must select the correct Mailing Preference', 'error', true);
return false;
}
if ($("#"+field[i]).val() == "" || !$("#"+prefs[i]).is(":checked")) {
$("#MailPrefBusi").validationEngine({promptPosition : "bottomRight", scroll: true}).validationEngine('showPrompt', 'You must select the correct Mailing Preference', 'error', true);
return false;
}
}
return true;
}
I'm using jQueryValidationEngine but it also doesn't correctly validate them. I only use it to show the validation error for these fields.
Here is the criteria:
If the MailPrefBusi is checked, then the BusinessAddress1 must be filled in.
If the MailPrefHome is checked, then the HomeAddress1 must be filled in.
If no MailPrefxxx is checked, show error. If no xxxAddress1 is filled, Show error.
It looks like your second if statement if ($("#"+field[i]).val() == "" || !$("#"+prefs[i]).is(":checked")) { is returning false when you don't want it to. You should be able to accomplish what you want using this:
function checkMailingPrefs() {
var prefs = ["MailPrefHome", "MailPrefBusi"];
var field = ["HomeAddress1", "BusinessAddress1"];
for (i = 0; i < 2; i++) {
if ($("#"+prefs[i]).is(":checked") && $("#"+field[i]).val() == "") {
// enhanced validation function call here
return false;
}
}
//if the user hasnt checked anything, you can remove this if the form should validate without the user having to set a radio button
if(!$("#MailPrefBusi, #MailPrefHome").is(":checked")) {
// enhanced validation function call here
return false
}
return true;
}
You can see it working at this JS Fiddle: https://jsfiddle.net/h0vj9r35/
Hope that helps!
If you are trying to figure out whether the corresponding fields are filled based on checkbox values in a scenario where you have n no. of checkboxes and fields and would like to avoid hardcoding of values, you may use the following:
var prefs = ["MailPrefHome", "MailPrefBusi"];
var field = ["HomeAddress1", "BusinessAddress1"];
var allEmpty = false;
var valueError = ""
for (i = 0; i < 2; i++)
{
if ($("#"+field[i]).val() == "" || !$("#"+prefs[i]).is(":checked")) {
if(!$("#"+prefs[i]).is(":checked"))
valueError += prefs[i] + "," ;
else if($("#"+field[i]).val() == "")
valueError += field[i];
allEmpty = true;
}
if ($("#"+prefs[i]).is(":checked") && $("#"+field[i]).val() == "")
{
$("#" + prefs[i]).prop('checked', false);
allEmpty = false;
alert("Need to enter " + field[i]);
return false;
}
if((i == 1) && allEmpty)
{
alert("You need to select " + valueError);
return false;
}
}
return true;
http://jsfiddle.net/n0303qd6/1/
I have a page that I need to disable the email field on. It needs to be readonly and dimmed. I've never worked with PHP before, and I assume that's what this code is, but, I'm not sure where I would disable the email field. Here's the code I have so far:
/**
* Validate our form fields
*/
var emailField, passwordField, confirmField, formfields = FormField.GetValues(%%GLOBAL_EditAccountAccountFormFieldID%%);
for (var i=0; i<formfields.length; i++) {
var rtn = FormField.Validate(formfields[i].field);
if (!rtn.status) {
alert(rtn.msg);
FormField.Focus(formfields[i].field);
return false;
}
if (formfields[i].privateId == 'EmailAddress') {
emailField = formfields[i];
} else if (formfields[i].privateId == 'Password') {
passwordField = formfields[i];
} else if (formfields[i].privateId == 'ConfirmPassword') {
confirmField = formfields[i];
}
}
if(emailField.value.indexOf("#") == -1 || emailField.value.indexOf(".") == -1) {
alert("%%LNG_AccountEnterValidEmail%%");
FormField.Focus(emailField.field);
return false;
}
if((passwordField.value != "" || confirmField.value != "") && (passwordField.value != confirmField.value)) {
alert("%%LNG_AccountPasswordsDontMatch%%");
FormField.Focus(confirmField.field);
return false;
}
return true;
}
%%GLOBAL_FormFieldRequiredJS%%
//]]>
To display a disabled texfield, you should output:
echo '<input type="email" name="name_of_field" value="email_to_display#gmail.com" disabled>';
Example:
See here (and have a look at the code):
Example
Perhaps if we had a link to the website we could have a look a it :)
I have the following form:
<form name="survey1" action="add5up.php" method="post" onsubmit="return validateForm()">
<div id="question">Q1) My programme meets my expectations</div><br />
Always<INPUT TYPE = 'Radio' Name ='q1' value= 'a'>
Usually<INPUT TYPE = 'Radio' Name ='q1' value= 'b'>
Rarely<INPUT TYPE = 'Radio' Name ='q1' value= 'c'>
Never<INPUT TYPE = 'Radio' Name ='q1' value= 'd'>
<input type="submit" value="addData" />
</form>
I am trying to validate whether a Radio button has been selected.
The code I am using:
<script type="text/javascript">
function validateForm()
{
if( document.forms["survey1"]["q1"].checked)
{
return true;
}
else
{
alert('Please answer all questions');
return false;
}
}
</script>
This is not working. Any ideas?
When using radiobuttons you have to go through to check if any of them is checked, because javascript threats them as an array:
<script type="text/javascript">
function validateRadio (radios)
{
for (i = 0; i < radios.length; ++ i)
{
if (radios [i].checked) return true;
}
return false;
}
function validateForm()
{
if(validateRadio (document.forms["survey1"]["q1"]))
{
return true;
}
else
{
alert('Please answer all questions');
return false;
}
}
</script>
Regards
My solution for validation complex forms include radios.
Usage is simple, function return TRUE/FALSE after validation.
var rs_target is ID of form
scTo is my custom func to scroll to ID, you can use own function to show/scroll errors
scTo("#"+err_target);
Error box will be like
<div class="rq_message_box rq_message_box_firstname display-none">err message</div>
Validation
var validation = validateForm(rs_target);
if(validation == false){
return false;
}
Function
function validateForm(rs_target) {
var radio_arr = [];
var my_form = $("#"+rs_target);
my_form = my_form[0];
$(".rq_message_box").hide(); //clear all errors
//console.log(my_form);
var err = false;
var err_target = "";
for (key in my_form) {
//console.log("do");
if(!my_form[key]||my_form[key]==null||err){
break;
}
//console.log(my_form[key].name);
var x = my_form[key].value;
//console.log(x);
if(my_form[key].type == "radio"){
//console.log("radio");
if(radio_arr[my_form[key].name] != true){
radio_arr[my_form[key].name] = null;
}
if(my_form[key].checked){
radio_arr[my_form[key].name] = true;
}
}else{
if (x == null || x == "") {
//console.log(form[key].name.toString() + " must be filled out");
err = true;
err_target = my_form[key].name;
//return false;
}
}
}
//console.log(radio_arr);
var rad_err = false;
for (key in radio_arr) {
if(rad_err){
break;
}
var x = radio_arr[key];
if (x == null || x == "") {
//console.log("RADIO> "+key + " must be filled out");
rad_err = true;
err_target = key;
}
}
if(err || rad_err){
// some error stuff, for me show prepared error/help box with class [".rq_message_box_"+err_target] / err_target is name of input like [.rq_message_box_firsname]
$(".rq_message_box_"+err_target).show(); //show error message for input
scTo("#"+err_target); //scroll to - custom func
return false;
}else{
return true;
}
}
I am trying to do a Javascript form validation, and I want to set the formValue to 0 in several cases. That is, if ANY of the required fields are not filled out, the value should go to 0.
function formValidation() {
var formValue = 1;
if (document.getElementById('orgname').value == '') formValue = 0;
else if (document.getElementById('culture[]').value == '') formValue = 0;
else if (document.getElementById('category[]').value == '') formValue = 0;
else if (document.getElementById('service[]').value == '') formValue = 0;
if (formOkay == 1) {
return true;
} else if (formOkay == 0) {
alert('Please fill out all required fields');
return false;
}
}
Is there a more elegant way to do this?
EDIT: Script does not appear to be working, now.
You can do some looping:
var toCheck = ['orgname', 'culture[]', 'category[]', 'category[]']
for(var id in toCheck )
{
if(document.getElementById(id).value == ''){
formValue = 0;
break;
}
}
A more elegant way can be that you specify a 'required' class on each input that you want to check and than do the following using jQuery:
$(document).ready(function(){
var toCheck = $('.required');
var formValue = 1;
$.each(toCheck, function(index, element){
if(element.val() == '')
formValue = 0;
});
});
I've done this in other languages using boolean logic, taking advantage of the & operator. It always returns false if any of the values are false.
Something like:
function formValidation() {
var formValue = true;
formValue &= document.getElementById('orgname').value != '';
formValue &= document.getElementById('culture[]').value != '';
formValue &= document.getElementById('category[]').value != '';
formValue &= document.getElementById('service[]').value != '';
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
This has the advantage of working for other scenarios where your logic is more complicated. Anything that evaluates in the end to true/false will fit right in with this solution.
Then I'd work on reducing logic duplication:
function formValidation() {
var formValue = true;
var elementIdsToCheck = ['orgname', 'culture[]', 'category[]', 'category[]'];
for(var elementId in elementIdsToCheck) {
formValue &= document.getElementById(elementId).value != '';
}
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
Something like this should help (this assumes that value attribute is available on the referenced elements):
var ids = ["orgname", "culture[]", "category[]", "service[]"],
formValue = 1; // default to validation passing
for (var i = 0, len = ids.length; i < len; i++) {
if (document.getElementById(ids[i]).value === "") {
formValue = 0;
break; // At least one value is not specified so we don't need to continue loop
}
}
Building upon #Baszz's second answer using jQuery, you could also build a more generic solution using HTML5 data- attributes:
$(function() {
$('form').submit(function() {
var toValidate = $(this).find('input[data-validation]');
for(var i=0; i<toValidate.length; i++) {
var field = $(toValidate[i]);
if(field.val().search(new RegExp(field.data('validation'))) < 0) {
alert("Please fill out all required fields!");
return false;
}
}
});
});
You can then specify regular expressions in your markup:
<form>
<input type="text" data-validation=".+" />
</form>
For required fields you can use ".+" as a regular expression, meaning the user has to enter at least one character, but you can of course use the full potential of regular expressions to check for valid email addresses, phone numbers or zip codes etc...