1

What is the purpose of $(elem) and when do I use it?

I have a problem with my javascript function, I have 3 forms and this 3 forms sometimes share the same field classes, thus when I try to do a verification for 1 of the form even though it is properly filled up it will return an error since the function will get the class of the other form, one of my friend said to use $(elem) since it worked for his problem, but I do not know how to use $(elem), when to use it, and how does it work.

It would be really great if anyone could explain this to me.

an example would also be appreciated :)

Example:

function dispFields(a, b, c, z, ch) 
{
    var valid;
    var blanks = Array();
    var blanks2 = Array();
    var email_reg = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
    var myVal = $('#'+a).find('input.required').map(function() {
                               return $(this).val();
                               }).get().join(',');
    var myTitle = $('#'+a).find('input.required').map(function() {
                               return $(this).attr("title");
                               }).get().join(',');

    var myEmail = $('#'+a).find('input.email-field').map(function() {
                               return $(this).val();
                               }).get().join(',');

    var myEmailtitle = $('#'+a).find('input.email-field').map(function() {
                               return $(this).attr("title");
                               }).get().join(',');

        var email_val = myEmail.split(',');
        var email_title = myEmailtitle.split(',');
        var email_error = email_val.length;
        var error_form = myVal.split(',');
        var error_title = myTitle.split(',');
        var errorlength = error_form.length;

        String.prototype.email_match = function(s){
           return this.match(s)!==null 
        }
        for(y=0;y<email_error;y++){
            if (!('indexOf' in Array.prototype)) {
                Array.prototype.indexOf= function(finds, is /*opt*/) {
                    if (is===undefined) is= 0;
                    if (is<0) is+= this.length;
                    if (is<0) is= 0;
                    for (var n= this.length; is<n; is++)
                        if (is in this && this[is]===finds)
                            return is;
                    return -1;
                };
            }
            if((error_title.indexOf(email_title[y])) == -1){    
                if(email_val[y] == ''){
                    valid = true;
                }else{
                    if(email_reg.test(String(email_val[y]).toLowerCase())==false){
                        blanks2[y] = email_title[y]+" - Should be valid email";
                        valid = false;
                    }
                }
            }
        }
        for(x=0;x<errorlength;x++){
            if(error_form[x] == ''){
                    if(myTitle == ''){
                        valid = true;
                    }else{
                        blanks[x] = "Required - "+error_title[x];
                        valid = false;
                    }
            }else{
                var myBool = (String(error_title[x]).toLowerCase()).email_match("email");
                if(myBool == true){
                    if(email_reg.test(String(error_form[x]).toLowerCase())==false){
                        blanks[x] = error_title[x]+" - Should be valid email";
                        valid = false;
                    }
                }else{
                    if(blanks == ''){
                        valid = true;
                    }
                }
            }   
        }
        if(blanks == '' && blanks2 == ''){
            valid = true;
            }else{
            valid = false;
        }

        var blankc = blanks.concat(blanks2);
        var requiredS = blankc.toString();
        var nblank = requiredS.split(',').join("\n");

        if(valid != true){  
            alert("Please review:\n\n"+nblank);
            document.getElementById(a).style.display = "";
            document.getElementById(b).style.display = "none";
        }else{
            var ssplits = z.split(',');
            var fieldlengths = ssplits.length;
            var indexes = fieldlengths - 1;
            var d;
            var e;
            d=parseInt(c,10)+1;
            e=d-1;

            if(b == ssplits[indexes]){
                $("#step"+d).addClass("active");
                $("#step"+e).removeClass("active");
                document.getElementById(a).style.display = "none";
                document.getElementById(b).style.display = "";
                document.getElementById("tbutton").style.display = "";
                document.getElementById("tcont").style.display = "none";    
                document.getElementById("captchas").style.display = "none";     
            }

            $("#step"+d).addClass("active");
            $("#step"+e).removeClass("active");
            document.getElementById(a).style.display = "none";
            document.getElementById(b).style.display = "";
            if(b == ch){
                document.getElementById("captchas").style.display = "";     
            }
        }
    return false;
}

Now this function is called whenever i submit a form, but in a page i can have 2 or 3 forms that may have the class "required" thus even if the fields in the form is filled up it will still alert an error because it is getting the classes of the fields of the other forms.

magicianiam
  • 1,474
  • 7
  • 33
  • 70
  • It makes possible to carry out multiple operations on the children of any particular parent (within the DOM) while retaining the original subject of the chain – Anujith Dec 13 '12 at 18:53
  • 1
    Please show the relevant bit of your source code. An example will then be easier to provide. – gilly3 Dec 13 '12 at 18:59
  • @A.V would you mind giving an example as an answer. thank you :) – magicianiam Dec 13 '12 at 19:00
  • 3
    For a second I thought you were asking _what is the purpose of $(life)_? – Salman A Dec 13 '12 at 19:01
  • 1
    @SalmanA lol. i try to find the meaning of life everyday i go to the bathroom. – magicianiam Dec 13 '12 at 19:01
  • @gilly3 will do now. sorry for lacking information – magicianiam Dec 13 '12 at 19:02
  • @magicianIam: Please tell us what library you are using. Many common ones do provide a `$` function, most notably jQuery and Prototype. – Bergi Dec 13 '12 at 19:07
  • @Bergi i am using the latest jquery plugin v1.8.3. or is that what you meant by library? – magicianiam Dec 13 '12 at 19:09
  • @magicianIam: [Yes](http://jquery.com/). Not sure why you call it a plugin. – Bergi Dec 13 '12 at 19:12
  • @Bergi sorry, got used to it. didn't really knew it was the wrong word. – magicianiam Dec 13 '12 at 19:16
  • Not related to your question, but [don't validate email addresses with regular expressions](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address). Validate email addresses by sending a verification email from the server and simply check for `/.@./` in javascript. – gilly3 Dec 13 '12 at 19:17
  • @gilly3 i dont send verifaction mail though, but i do check for @ and it is in the latter part of the code. – magicianiam Dec 13 '12 at 19:23
  • Please post the *relevant* bit of code, which would include the code where you alert the error as well as the logic that decides whether the form is valid. – gilly3 Dec 13 '12 at 19:24
  • @magicianIam - Your regex is *too strict*. For example, an email address such as `my+email@somedomain.com` would not pass your regex because it contains a `+` which your regex does not allow even though it is commonly used in email addresses. – gilly3 Dec 13 '12 at 19:28
  • @gilly3 never knew "+" is often used in email address. will add that to the exemption. thank you for that info. let me edit the post again – magicianiam Dec 13 '12 at 19:32
  • 1
    Even with the `+` added to your regex, it is still simultaneously too strict and not strict enough. For example, too strict: `.museum` and `.travel` are both valid TLDs but emails from these domains would be marked as invalid. Email addresses may contain quotes, spaces, diacritic characters, and all sort of special characters, but your regex excludes these. Not strict enough: `.aa` is *not* a valid TLD, but your regex allows it. It's better to be not strict enough than too strict. If you prevent a user from registering with their valid and working email address, you risk losing customers. – gilly3 Dec 13 '12 at 21:08

2 Answers2

6

$ is (usually) the jQuery function.

If you're using jQuery, then $(elem) will wrap elem as a jQuery object, and give you access to all of its utility methods.

Your friend was probably recommending that you use jQuery so you'd be able to do things like:

if ($(elem).hasClass('<your validation class>')) {

EDIT - looking at the code you just added, it looks like you're already using jQuery. Without more context of what your friend said it's hard to surmise what was meant.

If you have a specific question on how to accomplish something with jQuery you could always post a new question with a more narrowed-down code snippet.

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
  • will that then only get the classes from that element and not from other element that share the same classes? he was using this:$(elem).find('tform_id').val() – magicianiam Dec 13 '12 at 18:59
  • @magicianIam - probably. I'm not sure exactly what you mean, but yeah, using jQuery, checking if a given class is on an element, adding a class, toggling a class, etc etc etc is very easy. – Adam Rackis Dec 13 '12 at 19:00
0

** $ helps you get a handler for an element combined with a selector.** For example is you have an element with a class A, you can use the $ to get a handler to that element -> $(".A") [ . -> the class selector, # -> the id selector ]. So in order to use jquery you have to use the the $ and a selector in order to manipulate an element, i.e $(".A").text("myText") -> sets the text of all the elements with the class A

Demian Flavius
  • 785
  • 1
  • 10
  • 17