webdevRefinery Forum: Trying to insert code before the containing div of a $(#FieldID) selected field - webdevRefinery Forum

Jump to content

  • 2 Pages +
  • 1
  • 2
  • You cannot start a new topic
  • You cannot reply to this topic

Rate Topic: -----

User is offline gushort 

  • Group: Members
  • Posts: 452
  • Joined: 05-January 11
  • LocationToronto

Posted 26 April 2012 - 11:18 PM (#1)

Trying to insert code before the containing div of a $(#FieldID) selected field


(PLEASE JUST READ "SIMPLIFIED QUESTION")
SIMPLIFIED QUESTION: How can I get the error message to display before the black box? (code here)


You may be familiar with it from a couple of other posts I have made, it is a jQuery/Bootstrap2 based javascript for validating fields in a form. You can pass a message to display on errors, a regex to use for validation, the div class of the field's container, the Bootstrap2 message class (usually "help-inline" or "help-block"), and a boolean to get the validator only to check for errors upon form submission (instead of "live").

I currently have to disable the "live" option, so it doesn't end up looking like this (repeating error message) if the user keeps entering invalid info, but I would prefer to have it functioning the way it was designed to. :)

I have been using this site (browz.in) to play around with the code and try to figure out how to get it working properly - ignore the other stuff on there, I'm just using it as my testing ground for now.

Here is the code. What i have done, and what I want it to do, follows ...

/**
 * jquery.validate.js for js Bootstrap form validation
 *
 * @author GeekTantra
 * @date 20 September 2009
 * http://www.geektantra.com/2009/09/jquery-live-form-validation/
 * Modified by dsmith: added support for twitter boostrap
 */
(function(jQuery){
    var ValidationErrors = new Array();
    jQuery.fn.validate = function(options){
        options = jQuery.extend({
            expression: "return true;",
            message: "",
            error_message_class: "help-inline",
            error_container_class: "control-group",
            live: true
        }, options);
        var SelfID = jQuery(this).attr("id");
        var unix_time = new Date();
        unix_time = parseInt(unix_time.getTime() / 1000);
        if (!jQuery(this).parents('form:first').attr("id")) {
            jQuery(this).parents('form:first').attr("id", "Form_" + unix_time);
        }
        var FormID = jQuery(this).parents('form:first').attr("id");
        if (!((typeof(ValidationErrors[FormID]) == 'object') && (ValidationErrors[FormID] instanceof Array))) {
            ValidationErrors[FormID] = new Array();
        }
        if (options['live']) {
            if (jQuery(this).find('input').length > 0) {
                jQuery(this).find('input').bind('blur', function(){
                    if (validate_field("#" + SelfID, options)) {
                        if (options.callback_success) 
                            options.callback_success(this);
                    }
                    else {
                        if (options.callback_failure) 
                            options.callback_failure(this);
                    }
                });
                jQuery(this).find('input').bind('focus keypress click', function(){
                    jQuery("#" + SelfID).next('.' + options['error_message_class']).remove();
                    jQuery("#" + SelfID).parents("." + options['error_container_class']).removeClass('error');
                });
            }
            else {
                jQuery(this).bind('blur', function(){
                    validate_field(this);
                });
                jQuery(this).bind('focus keypress', function(){
                    jQuery(this).next('.' + options['error_message_class']).fadeOut("fast", function(){
                        jQuery(this).remove();
                    });
    				jQuery(this).parents("." + options['error_container_class']).removeClass('error');
                });
            }
        }
        jQuery(this).parents("form").submit(function(){

            if (validate_field('#' + SelfID)) {			
                return true;
			}
            else 
                return false;
        });
        function validate_field(id){
            var self = jQuery(id).attr("id");
            var expression = 'function Validate(){' + options['expression'].replace(/VAL/g, 'jQuery(\'#' + self + '\').val()') + '} Validate()';
            var validation_state = eval(expression);
            if (!validation_state) {
                if (jQuery(id).next('.' + options['error_message_class']).length == 0) {
                    jQuery(id).before('<span class="' + options['error_message_class'] + '">' + options['message'] + '</span>');
					jQuery(id).parents("div ." + options['error_container_class']).addClass("error")
                }


                if (ValidationErrors[FormID].join("|").search(id) == -1) 
                    ValidationErrors[FormID].push(id);
                return false;
            }
            else {
                for (var i = 0; i < ValidationErrors[FormID].length; i++) {
                    if (ValidationErrors[FormID][i] == id) 
                        ValidationErrors[FormID].splice(i, 1);
                }
                return true;
            }
        }
    };
    jQuery.fn.validated = function(callback){
        jQuery(this).each(function(){
            if (this.tagName == "form") {
                jQuery(this).submit(function(){
                    if (ValidationErrors[jQuery(this).attr("id")].length == 0) 
                        callback();
					return false;
                });
            }
        });
    };
})(jQuery);

/*
 * jquery.validate.functions.js - provides helper methods for date and radio button validation to script above
 *
 * @author GeekTantra
 * @date 24 September 2009
 */
/*
 * This functions checks where an entered date is valid or not.
 * It also works for leap year feb 29ths.
 * @year: The Year entered in a date
 * @month: The Month entered in a date
 * @day: The Day entered in a date
 */
function isValidDate(year, month, day){
    var date = new Date(year, (month - 1), day);
    var DateYear = date.getFullYear();
    var DateMonth = date.getMonth();
    var DateDay = date.getDate();
    if (DateYear == year && DateMonth == (month - 1) && DateDay == day) 
        return true;
    else 
        return false;
}

/*
 * This function checks if there is at-least one element checked in a group of check-boxes or radio buttons.
 * @id: The ID of the check-box or radio-button group
 */
function isChecked(id){
    var ReturnVal = false;
    $("#" + id).find('input[type="radio"]').each(function(){
        if ($(this).is(":checked")) 
            ReturnVal = true;
    });
    $("#" + id).find('input[type="checkbox"]').each(function(){
        if ($(this).is(":checked")) 
            ReturnVal = true;
    });
    return ReturnVal;
}


The function was designed to place a Bootstrap2 formatted error message after (but inline with) the input/selection field container being validated when the BS2 "help-inline" class is specified, or under the field if the BS2 "help-block" class is used. And it works fairly well for basic horizontal forms with spaced out fields and control/submit buttons in their own area.

However, I wanted to use the function with a single field, one-line with submit button directly adjacent to input box, type form (see this site). I would like to have the error message placed before the input field, instead of after it, so as not to break up the unified "one box" input/submit design.

One problem though, I know practically no javascript - all my js knowledge is from reading stuff here and skimming a few intro tutorials over the last few months as time permitted (meaning I could usually only spend an hour or two on it every one or two weeks :P ).

Right now the only change I made with the above code was replacing all ".after" calls with ".before", which, to my surprise, actually worked out ... kind of :D As I mentioned before, if the user keeps trying to enter invalid info the message keeps repeating and doesn't reset.

So ....

oh, before I forget ... how do I display variable values using the js console? print($var)?
0


User is offline gushort 

  • Group: Members
  • Posts: 452
  • Joined: 05-January 11
  • LocationToronto

Posted 27 April 2012 - 09:20 PM (#2)

Nobody want to offer some advice, not even about how to display variables in the Safari js console?

I assume it is the following part of the function that I should be concentrating on, but I'm not sure why it isn't working ...

  jQuery(this).bind('blur', function(){
                    validate_field(this);
                });
                jQuery(this).bind('focus keypress', function(){
                    jQuery(this).next('.' + options['error_message_class']).fadeOut("fast", function(){
                        jQuery(this).remove();


I guess I should check to see exactly what the ".bind", ".next", and 'blur' parts do, and why it isn't finding the error div and ".remove" ing it
0


User is offline gushort 

  • Group: Members
  • Posts: 452
  • Joined: 05-January 11
  • LocationToronto

Posted 02 May 2012 - 05:29 PM (#3)

Alright, putting aside a little time to take another look at how to get this to work properly.

First question, is it really necessary to create a unique form ID using the unix_time stuff?

Plus I still need to figure out what exactly the .bind/blur and .next parts do ....
0


User is offline gushort 

  • Group: Members
  • Posts: 452
  • Joined: 05-January 11
  • LocationToronto

Posted 02 May 2012 - 10:26 PM (#4)

Ok, I'm back :) But no js experts seem to have been around :(

I have decided the best way to tackle this is to strip the original function down so that it isn't a multi-field handling validator. This makes sense, as I will only be checking/validating one field - the email address field.

Oh hell, maybe it would be easier if I just scrapped this validator "live" function, and just looked at other jQuery options already out there .... I'm getting a head ache.
0


User is offline gushort 

  • Group: Members
  • Posts: 452
  • Joined: 05-January 11
  • LocationToronto

Posted 02 May 2012 - 11:52 PM (#5)

I have cut down the code to this, so far:

(function(jQuery) {
    var ValidationErrors = new Array();
    jQuery.fn.validate = function(options) {
        options = jQuery.extend({
            expression: "return true;",
            message: "",
            error_message_class: "help-inline",
            error_container_class: "control-group"
        }, options);
        var SelfID = jQuery(this).attr("id");
        var FormID = jQuery(this).closest('form').attr("id");
        if (!((typeof(ValidationErrors[FormID]) == 'object') && (ValidationErrors[FormID] instanceof Array))) {
            ValidationErrors[FormID] = new Array();
        }
        jQuery(this).parents("form").submit(function() {

            if (validate_field('#' + SelfID)) {
                return true;
            }
            else return false;
        });

        function validate_field(id) {
            var self = jQuery(id).attr("id");
            var expression = 'function Validate(){' + options['expression'].replace(/VAL/g, 'jQuery(\'#' + self + '\').val()') + '} Validate()';
            var validation_state = eval(expression);
            if (!validation_state) {
                if (jQuery(id).next('.' + options['error_message_class']).length == 0) {
                    jQuery(id).before('<span class="' + options['error_message_class'] + '">' + options['message'] + '</span>');
                    jQuery(id).parents("div ." + options['error_container_class']).addClass("error")
                }
                if (ValidationErrors[FormID].join("|").search(id) == -1) ValidationErrors[FormID].push(id);
                return false;
            }
            else {
                for (var i = 0; i < ValidationErrors[FormID].length; i++) {
                    if (ValidationErrors[FormID][i] == id) ValidationErrors[FormID].splice(i, 1);
                }
                return true;
            }
        }
    };
    jQuery.fn.validated = function(callback) {
        jQuery(this).each(function() {
            if (this.tagName == "form") {
                jQuery(this).submit(function() {
                    if (ValidationErrors[jQuery(this).attr("id")].length == 0) callback();
                    return false;
                });
            }
        });
    };
})(jQuery);


$(function() {
    $("#email").validate({
        expression: "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\@[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/) && VAL) return true; else return false;",
        message: "Error! (proper email required)"
    });
});​


I don't think that there is a need for the "ValidationErrors" array, since we are only working with one field, but will leave it in for now.

It is a bit easier to see what is going on.

Right now, I'm thinking that adding an "else" condition, that will remove the "inline-error" if it exists. to the following:

 if (jQuery(id).next('.' + options['error_message_class']).length == 0) {
                    jQuery(id).before('<span class="' + options['error_message_class'] + '">' + options['message'] + '</span>');
                    jQuery(id).parents("div ." + options['error_container_class']).addClass("error")
                }


but I may try removing the "ValidationErrors" first....
0


User is offline gushort 

  • Group: Members
  • Posts: 452
  • Joined: 05-January 11
  • LocationToronto

Posted 03 May 2012 - 01:19 AM (#6)

Well, I think I figured out the problem. All I needed to do was change the ".next" function to a ".prev" function instead, and I no longer get multiple occurrences of the error messages.

I'm still going to see what else can be 'trimmed' from the function...and I still need to figure out how to place the 'inline-help' span code before the envelope icon (<i>) code.
0


User is offline gushort 

  • Group: Members
  • Posts: 452
  • Joined: 05-January 11
  • LocationToronto

Posted 03 May 2012 - 04:46 PM (#7)

Can someone at least point me to the relevant part of the jQuery documentation that would show me the appropriate function to use in order to properly select the "control-group" div that the field being validated is contained in (see below):

<form id="Form1" class="form-inline" method="POST" action="">
    <fieldset>
        <div class="control-group">
            <div class="controls pull-right">
                <div class="input-prepend input-append">
                    <span class="add-on"><i class="icon-envelope icon-large"></i></span>
                    <input class="span3" id="email" name="email" type="email" required placeholder="Enter your email address">
                    <button class="btn btn-large btn-inverse" type="submit">Subscribe!</button>
                </div>
            </div>
        </div>
    </fieldset>
</form>​


If someone does, I promise to abandon this thread and never ask for any javascript help here again :)
0


User is offline Renegade 

  • 418 I'm a teapot
  • Group: Members
  • Posts: 748
  • Joined: 08-March 10
  • Expertise:HTML,CSS,PHP,Javascript,Node.js,SQL,Graphics

Posted 03 May 2012 - 05:13 PM (#8)

Sorry for leaving you hanging here dude, I've been up to my neck with schoolwork. You know this isn't a good reflection of the wdR community. That post from dida wasn't very helpful either. <_<

If I picked up your last post correctly, you need to select a
div
? I think someone may need to scratch up on their jQuery 101. jQuery selects elements via dollar sign, $. Example,
$("div-selector")
. http://api.jquery.com/jQuery/

I'm pretty sure I'm missing something but for now, I need to catch up on some sleep. :(
http://adriancooney.ieGithubTwitterDribbbleForrst
We all die. The goal isn't to live forever. The goal is to create something that will.

Array(16).join({}-{}) + " Batman!";
0


User is offline gushort 

  • Group: Members
  • Posts: 452
  • Joined: 05-January 11
  • LocationToronto

Posted 03 May 2012 - 05:30 PM (#9)

View PostRenegade, on 03 May 2012 - 05:13 PM, said:

Sorry for leaving you hanging here dude, I've been up to my neck with schoolwork. You know this isn't a good reflection of the wdR community. That post from dida wasn't very helpful either. <_<

If I picked up your last post correctly, you need to select a
div
? I think someone may need to scratch up on their jQuery 101. jQuery selects elements via dollar sign, $. Example,
$("div-selector")
. http://api.jquery.com/jQuery/

I'm pretty sure I'm missing something but for now, I need to catch up on some sleep. :(


Wow, there is life on Wdr :lol: I was starting to think the site had shutdown, and they just forgot to tell me :D I guess this is what happens when you just have a small group of very helpful people who actually post solutions, and then somehow each member of that group gets busy with 'the more important things in life' all at the same time :P

As for your response, what I would like to ideally do is insert or remove, depending upon its current state, a <span> with a class of "inline-help" immediately after the div which belongs to #Form1 (in above example), has a "control-group" class, AND encloses/surrounds/"is higher up in the chain" the input field being validated by the function. Here is the jsFilddle repo I've been using to test things with. I have tried the ".closest" function, but it isn't acting the way I thought it would.

I would also like to know how to display, in an alert() or even in the Safari js console, the element that "this" (as in $(this)) is referring to, for debugging purposes.

Thanks for your help.
0


User is offline Renegade 

  • 418 I'm a teapot
  • Group: Members
  • Posts: 748
  • Joined: 08-March 10
  • Expertise:HTML,CSS,PHP,Javascript,Node.js,SQL,Graphics

Posted 03 May 2012 - 05:44 PM (#10)

So in essence, your trying to show help when a field is being validated (I.e. focused or changed)? And you want insert before/after the currently highlighted field, with the parent "control-group", a
span
with the help information? Still a bit confused to what you're actually trying to achieve.

As for the debugging, you may want to try
console.log
. It is extremely useful for debugging, necessary even. I have no idea how you've managed to get this far without using it! The (chrome/firebug) console can display any data you want with the
log
function, including jQuery wrapped elements such as
$(this)
. It's as simple as:

console.log($(this));


I hope I'm actually answering your questions here! xD
http://adriancooney.ieGithubTwitterDribbbleForrst
We all die. The goal isn't to live forever. The goal is to create something that will.

Array(16).join({}-{}) + " Batman!";
0


User is offline gushort 

  • Group: Members
  • Posts: 452
  • Joined: 05-January 11
  • LocationToronto

Posted 03 May 2012 - 05:58 PM (#11)

View PostRenegade, on 03 May 2012 - 05:44 PM, said:

So in essence, your trying to show help when a field is being validated (I.e. focused or changed)? And you want insert before/after the currently highlighted field, with the parent "control-group", a
span
with the help information? Still a bit confused to what you're actually trying to achieve.


Yes, I'm trying to place the "error" text (which will be in a <span class="inline-help"> element) before, instead of after, the current "focused" field, but also before the <span class="add-on"> and <div class="input-prepend input-append"> elements from example code above.

View PostRenegade, on 03 May 2012 - 05:44 PM, said:

As for the debugging, you may want to try
console.log
. It is extremely useful for debugging, necessary even. I have no idea how you've managed to get this far without using it! The (chrome/firebug) console can display any data you want with the
log
function, including jQuery wrapped elements such as
$(this)
. It's as simple as:

console.log($(this));


I hope I'm actually answering your questions here! xD


Thanks, I'll give it a try in Safari's console. As for getting this far without using, I come from an era when useful debuggers and IDEs had not become "ready for prime-time" yet :P
0


User is offline gushort 

  • Group: Members
  • Posts: 452
  • Joined: 05-January 11
  • LocationToronto

Posted 03 May 2012 - 08:05 PM (#12)

Well, this is one way to learn js :lol:

I've stripped down the original function, so that excess code doesn't throw me off while I'm trying to get it to work the way I need.

(function(jQuery) {
    jQuery.fn.validate = function(options) {
        options = jQuery.extend({
            expression: "return true;",
            message: "",
            error_message_class: "help-inline",
            error_container_class: "control-group"
        }, options);
        var SelfID = jQuery(this).attr("id");
        var FormID = jQuery(this).closest('form').attr("id");
        jQuery(this).parents("form").submit(function() {

            if (validate_field('#' + SelfID)) {
                return true;
            }
            else return false;
        });

        function validate_field(id) {
            var self = jQuery(id).attr("id");
            var expression = 'function Validate(){' + options['expression'].replace(/VAL/g, 'jQuery(\'#' + self + '\').val()') + '} Validate()';
            var validation_state = eval(expression);
            if (!validation_state) {
                if (jQuery(id).prev('.' + options['error_message_class']).length == 0) {
                    jQuery(id).before('<span class="' + options['error_message_class'] + '">' + options['message'] + '</span>');
                    jQuery(id).closest("div ." + options['error_container_class']).addClass("error")
                }
                return false;
            }
            else 
                return true;
            }
        }
})(jQuery);


$(function() {
    $("#email").validate({
        expression: "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\@[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/) && VAL) return true; else return false;",
        message: "Error! (proper email required)"
    });
});​


Also, finally figured out that "VAL" isn't actually part of js and was just a placeholder, created by the original function creator, to insert some jquery val() code using the "match()" function. Below is the actual js code used to set the variable "validation_state", where "regexp" is whatever regular expression you passed to the function - in this case an email format test.

function Validate() {
   if(jQuery('#email').val().match(/regexp/) && jQuery('#email').val()) return true;
     else return false;
} Validate()


I gotta say, this js syntax is going to make me loopy :P

SIMPLIFIED QUESTION: How can I get the error message to display before the black box? (code here)

:)
0


User is offline gushort 

  • Group: Members
  • Posts: 452
  • Joined: 05-January 11
  • LocationToronto

Posted 04 May 2012 - 03:53 AM (#13)

Note: the commented out function, in the jsFiddle javascript area, is just what the var "expression" ends up being, I forgot to remove it
0


User is offline gushort 

  • Group: Members
  • Posts: 452
  • Joined: 05-January 11
  • LocationToronto

Posted 04 May 2012 - 02:28 PM (#14)

Updated title...still need help.
0


User is offline gushort 

  • Group: Members
  • Posts: 452
  • Joined: 05-January 11
  • LocationToronto

Posted 04 May 2012 - 05:05 PM (#15)

You guys are going to force me to learn js, aren't you? :P
0


User is offline arronhunt 

  • I'm a httpster
  • Group: Moderators
  • Posts: 3398
  • Joined: 09-March 10
  • LocationLos Angeles, CA
  • Expertise:HTML,CSS,Javascript,Graphics,Flash

Posted 04 May 2012 - 05:10 PM (#16)

View Postgushort, on 04 May 2012 - 05:05 PM, said:

You guys are going to force me to learn js, aren't you? :P


You should know JS before jumping into JQuery.

Are you trying to place that validation tooltip before the text input (underneath the envelop)? If that's what you are trying to do it isn't possible as you can't style (at all) the default browser validation tooltips (src)

If that's not what you are trying to do...please post a super simple explanation below this. There is a LOT of code blocks on this thread that nobody really wants to read.
DO NOT OPEN THIS

Spoiler
0


User is offline gushort 

  • Group: Members
  • Posts: 452
  • Joined: 05-January 11
  • LocationToronto

Posted 04 May 2012 - 05:26 PM (#17)

View Postarronhunt, on 04 May 2012 - 05:10 PM, said:

You should know JS before jumping into JQuery.


I don't really want to use jQuery either, it just happened to be tool used to create the original form validation function I wanted to use - I don't really want to learn js or jQuery, I just wanted to get the above to work, as I really have no other need for it except form validation.
0


User is offline gushort 

  • Group: Members
  • Posts: 452
  • Joined: 05-January 11
  • LocationToronto

Posted 08 May 2012 - 06:28 PM (#18)

Picked up a JS manual, and have started down the road of learning yet another web language just to get this done.

Ugh. :(
0


User is offline Hyde 

  • Group: Members
  • Posts: 1562
  • Joined: 08-March 10

Posted 08 May 2012 - 07:04 PM (#19)

I'm very sorry that you couldn't find the help that you need here though...
Hyde | HTML & CSS | PHP & SQL | Objective-C | Java | Basic JavaScript
0


User is offline arronhunt 

  • I'm a httpster
  • Group: Moderators
  • Posts: 3398
  • Joined: 09-March 10
  • LocationLos Angeles, CA
  • Expertise:HTML,CSS,Javascript,Graphics,Flash

Posted 08 May 2012 - 08:51 PM (#20)

If you post a simplified explanation of what you are trying to achieve ill be more than happy to assist
DO NOT OPEN THIS

Spoiler
0


Share this topic:


  • 2 Pages +
  • 1
  • 2
  • You cannot start a new topic
  • You cannot reply to this topic

2 User(s) are reading this topic
0 members, 2 guests, 0 anonymous users


Enter your sign in name and password


Sign in options
  Or sign in with these services