1

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.

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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]);
});

1 Comment

If you use var divnum = 'out' + $(this).attr('id');, then divnum will be 'outdiv1' or 'outdiv2'. But outdivs['outdiv1'] and outdivs['outdiv2'] don't exist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.