Irfan Y
Irfan Y

Reputation: 1300

jquery single var for two ids

I have two variables for two different classes. I want to assign single variable two both classes.e.g, the classes "signup" and "join" should be accessed using single variable like singup.

<head>
<script>

    var signup = $("signup");
    var join = $("join");
    signup.on("click",function(){

        alert("Signup");

    })
    join.on("click",function(){

        alert("Signup");

    })

</script>
</head>

<body>

    <div class="signup">Signup</div>
    <div class="join">Join Now</div>

</body>

Upvotes: 2

Views: 2205

Answers (3)

meetmahpuppy
meetmahpuppy

Reputation: 428

You can't access it since you use $('join') instead of $('.join'). Anyway, you can make it like this.

1) Ugly Approach

var elements = [];

elements.push( $('.join')[0] );
elements.push( $('.signup')[0] );

iterate using .each function
$(elements).each(function() {
    $(this).on('click', function() {
        alert('Signup');
    });
});

2) Make a reference for the function

var signupClick = function() {
     alert('Signup');
});
$('.join').on('click', signupClick);
$('.signup').on('click', signupClick);

3) Comma separated

$('.join, .signup').on('click', function() {
        alert('Signup');
});

4) Add some class(prefered)

<div class="signup button">Signup</div>
<div class="join button">Join Now</div>

Then you can do some like this.

$('.button').on('click', function() { alert('Signup'); });

Upvotes: 0

rm-vanda
rm-vanda

Reputation: 3158

The correct way to select your elements is with the class selector. i.e.:

$(".signup")

as Arun noted, you could use the multiple selector, but there is really not much of a point in assigning those elements to variables.

Your code could be re-written like so:

$(".signup, .join").click(function() {
    alert("Signup"); 
});

Keep practicing -! Play around in your browser's javascript console - And heed the error log - !

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You can use multiple selector

var signup = $(".signup, .join");

Upvotes: 2

Related Questions