Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery .click pass variables

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

like image 786
russell Avatar asked Jan 15 '10 08:01

russell


2 Answers

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
like image 116
Doug Neiner Avatar answered Nov 08 '22 18:11

Doug Neiner


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

like image 31
Naeem Sarfraz Avatar answered Nov 08 '22 19:11

Naeem Sarfraz