javascript - Issue targeting specific selector jquery in dropdwon menu -


i have drop down menu jquery , want modify text in different way depending on selected in drop down menu.

the drop down menu works.

html code:

<div> <ul class="mymenu">     <li><a href="#">choose location</a>         <ul>             <li id="op1"><a href="#co">option1</a></li>             <li id="op2"><a href="#nk">option2</a></li>             <li id="op2"><a href="#so">option3</a></li>         </ul>     </li> </ul> </div> <div> <h1 id="text_to_change">welcome blabla</h1> </div>   

javascript code:

$(document).ready(function() { $('.mymenu li ul li').click( function(event){     $(document).find('#text_to_change').css('visibility', 'visible');     $('.mymenu').hide();     if ($(this) == '#op1'){         $('#text_to_change').text("text changed");     }     if ($(this) == '#op2'){         $('#text_to_change').text("text changed differently");     }     else{         $('#text_to_change').text("text changed differently again");     } }); });          

why ($(this) == '#op1') not work?

you trying compare jquery object $(this) string #op1

to id of element use:

$(this).attr('id'); 

it give id of element without #

also think second if needs else if { ...

$(document).ready(function() {  $('.mymenu li ul li').click( function(event){            console.log($(this).attr('id'), $(this).prop('id'));      $(document).find('#text_to_change').css('visibility', 'visible');      $('.mymenu').hide();      if ($(this).attr('id') == 'op1'){          $('#text_to_change').text("text changed");      }      else if ($(this).attr('id') == 'op2'){          $('#text_to_change').text("text changed differently");      }      else{          $('#text_to_change').text("text changed differently again");      }  });  });  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>  <div>  <ul class="mymenu">      <li><a href="#">choose location</a>          <ul>              <li id="op1"><a href="#co">option1</a></li>              <li id="op2"><a href="#nk">option2</a></li>              <li id="op2"><a href="#so">option3</a></li>          </ul>      </li>  </ul>  </div>  <div>  <h1 id="text_to_change">welcome blabla</h1>  </div>


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -