Mario.Rdz
Mario.Rdz

Reputation: 13

Jquery | Variable value working as a string instead of calling another variable

The Html:

<div id="div1" name="divname">Something</div>
<div id="div2" name="divname">Something else</div>

<div id="output"></div>

The Jquery:

$('[name="divname"]').click( function (){ 

   var divnum = $(this).attr('id'); 
   var divout = 'out' + divnum;

   var outdiv1 = 'first div clicked';
   var outdiv2 = 'second div clicked';

   $('#output').html(divout);

});

Desired Result after div1 got clicked:

<div id="output">first div clicked</div>

Actual Result:

<div id="output">outdiv1</div>


Help Please.

Upvotes: 1

Views: 241

Answers (2)

Oriol
Oriol

Reputation: 288570

You should do it this way:

$('[name="divname"]').click( function (){ 

  var divnum = $(this).attr('id'); 
  var out={div1:'first div clicked',div2:'second div clicked'}
  $('#output').html(out[divnum]);

});

That's because if you say...

var divout = 'out' + divnum;

... divout is a string.

But you want to access the variable whose name is the string which divout contains. So the easiest way is creating an object, because you can access its properties like this:

  1. obj.property
  2. obj['property']

So

  • If you know the name of the property:

    obj.property or obj['property']

  • If you don't know its name but you have a variable myvar which contains it:

    obj[myvar] (myvar = 'property')

EDIT: Anyway, in that case I would use that:

$('[name="divname"]').click( function (){ 

  var divnum = $(this).attr('id'); 
  $('#output').html((divnum=='div1'?'first':'second')+' div clicked');

});

It checks if divnum is 'div1' and, if yes, the result is 'first div clicked'. If not, 'second div clicked'.

This way you don't need any objects, only a conditional.

Upvotes: 1

Blender
Blender

Reputation: 298430

You aren't going to get anywhere good naming variables like that. If your variables have very similar names (var1, var2, var3, ...), you should either be using an object or an array to store them.

In this case, try using objects to create a mapping between names and values:

var outdivs = {
  'div1': 'first div clicked',
  'div2': 'second div clicked'
};

$('[name="divname"]').click(function() {
   var divnum = $(this).attr('id');

   $('#output').text(outdivs[divnum]);
});

Upvotes: 0

Related Questions