0

I have a label , that shows dynamic values based on user actions. For example 1 or 2. I would like to show div element with id="charts_div" if the label value is "1" I would like to hide div element, if the value is "2" This example is simplified as possible, so I could get basic idea where i am stuck

HTML

<label id="label"></label>
 <div id="chart1_div" style="width:100%; height:200px"></div>
 <div id="chart2_div" style="width:100%; height:200px"></div>

JQUERY

$(document).ready( function() {
$('#label').bind('change', function (e) { 
if ($('#label').text() == "1")
{
$('#chart1_div').show();
$('#chart2_div').hide();

}
else if $('#label').text()=="2")
{
  $('#chart1_div').hide();
  $('#chart2_div').show();
}         
}).trigger('change');
});
James Montagne
  • 77,516
  • 14
  • 110
  • 130
kaulainais
  • 115
  • 1
  • 2
  • 12
  • You have a round ( bracket missing on your second if (else if). instead of binding to a change event for a label (which will never fire) why not call a function that does that check where the label is changed? – developer82 Jan 20 '14 at 16:12

2 Answers2

3

You can't bind change event to an element that doesn't have that kind of event. Put this change logic inside the event that is actually doing the changing of the label's text.

tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

As it was said, you can't bind a change event to a label. Make whatever is changing your label also change the divs being shown. Supposing it's a button, do something like this:

HTML

<label id="myLabel">1</label>
<button id ="myButton">Toggle between 1 and 2</button>
<div id="chart1_div" style="width:100%; height:200px">a</div>
<div id="chart2_div" style="width:100%; height:200px">b</div>

JS

$(document).ready( function() {
    $("#myButton").click(function(){
        if ($('#myLabel').text() == '1')
        {
            $("#myLabel").text('2');
            $('#chart1_div').show();
            $('#chart2_div').hide();
        } else if ( $('#myLabel').text()=='2')
        {
            $("#myLabel").text('1');
            $('#chart1_div').hide();
            $('#chart2_div').show();
        }        
    });
});

Check out a live example on this jsfiddle ;)

chapulina
  • 45
  • 2
  • 7