views:

334

answers:

4

Hi folks, propb. very simple, but not for me. Looking to pass a variable on a click function to show either div a or div b based on the a link clicked. My code is something like this

$('.view').click(function() {
    var id = this.id.replace('view_', "");
if(id=1) { $('#show').show('slow'); }
if(id=2 ) { $('#show2').show('slow'); }
$('#categories').hide('slow');
    return false;
  });
  }); 

But OBVIOUSLY the if statements are wrong - I know that I am just using them as an example. Any suggerstions? Thanks in adavance

+5  A: 

You are assigning the value of 1 to id instead of testing for a match:

if(id = 1) {} // WRONG: this means if id is successfully SET to 1

Here is what it should look like:

$('.view').click(function() {
    var id = this.id.replace('view_', "");

    if(id == 1)       { $('#show').show('slow'); }
    else if(id == 2 ) { $('#show2').show('slow'); }

    $('#categories').hide('slow');

    return false;
});

If you find yourself making this mistake a lot, you should switch the test around:

if( 1 == id) {} // Works
if( 1 = id ) {} // Throws JS error instead of failing silently
Doug Neiner
+1 this post finally reveals why people write (1==id) instead of the other way round
Here Be Wolves
+2  A: 

try this...

var id = parseInt(this.id.replace('view_', ""), 10);
if(id === 1) { 
 $('#show').show('slow'); 
} else if(id === 2 ) { 
 $('#show2').show('slow'); 
}

1 '=' is used for assignment
2 '==' is comparison with type conversion
3 '===' is comparison without type conversion

Naeem Sarfraz
Perfect Naeem, thanks, works stright out of box. I am just learning JQuery/java so some of the lang is a bit strange for me as a PHP guyThanks again
russell
A: 

If your link id's are view_1 and view_2, then all should be fine here, except for the fact that you're using = rather than comparison ==.

If your show elements were called show1 and show2, rather than show and show2, you could of course do:

$('.view').click(function() {
    $('#show' + this.id.replace('view_','')).show('slow');
    $('#categories').hide('slow');
    return false;
});
David Hedlund
A: 

As Doug pointed out, the problem is in conditional assignment

You should also consider renaming your ids to directly match your view ids, so you can do it without test cases, only by string concatenation:'

$('.view').click(function() {
    var id = this.id.replace('view_', "");

    $('#show' + id).show('slow'); // doesn't have to use if statements

    $('#categories').hide('slow');

    return false;
});
Juraj Blahunka