chris Frisina
chris Frisina

Reputation: 19688

JQuery attr selector to string, stored as a variable, then passed into another JQuery selector

I want to use a JQuery selector to grab an elelement if it is clicked, check to make sure it has an appropriate class name (in this case jobtype), and if so, use its name attribute value as a selector, to hide() classes with values that are the same of the first selectors name attribute value.

Here is the code I have so far:

    $('fieldset.workexperience input').on('change', function() {
        // var jtaa = {"bit" : "Business Information Technology",
        //          "cs" : "Customer Service",
        //          "dev" : "Developer",
        //          "eng" : "Engineer",
        //          "mgr" : "Manager",
        //          "ocm" : "Organizational Change Management" };
        if ($(this).hasClass('jobtype')) {
            $($(this).attr("name")).hide();
        } else {

        }
    });

The var jtaa has keys and values. The keys represent the different possible "name" attrs. I would like when one is clicked, if its name is eng, then the JQuery selector should be $(.eng).hide(). When I type directly in the console, it works, however, directly from here, it errors out.

Upvotes: 0

Views: 305

Answers (1)

Baz1nga
Baz1nga

Reputation: 15579

$('fieldset.workexperience input').on('change', function() {
        // var jtaa = {"bit" : "Business Information Technology",
        //          "cs" : "Customer Service",
        //          "dev" : "Developer",
        //          "eng" : "Engineer",
        //          "mgr" : "Manager",
        //          "ocm" : "Organizational Change Management" };
        var obj=$(this);
        if (obj.hasClass('jobtype')) {
            $('.'+obj.attr("name")).hide();
        } else {

        }
    });

Notice the period . concantenation to the selector Also you might want to consider adding a not null check to make the code robust..

Upvotes: 2

Related Questions