Update of several IDs in Javascript

advertisements

I'm update few text in a page using <SPAN ID="idName"> based on dropdown selection ID, but only the first element ID changes. Using different ID's work but was hoping there is an easier solution. I am using twitter-bootstrap-3 for my dropdown menu.

Here's the HTML:

<ul class="nav nav-pills">
 <li class="dropdown menu-btn">
  <a href="#" class="dropdown-toggle" data-toggle="dropdown" >
      <span class="glyphicon glyphicon-map-marker"></span> <span id="SelectName"></span><b     class="caret"></b></a>
  <ul id="myCitylist" class="dropdown-menu">
        <li> <a href="#">San Jose</a> </li>
        <li> <a href="#">Silicon Valley</a> </li>
        <li> <a href="#">New York City</a> </li>
        <li> <a href="#">Paris</a> </li>
        <li> <a href="#">Silicon Valley</a> </li>
        <li> <a href="#">Tokyo</a> </li>
  </ul>
</li>
</ul>

Now we'll talk about <span id="SelectName"></span>

and javascript

 document.getElementById("SelectName").innerHTML = "San Francisco";

 $('#myCitylist li').on('click', function(){
    document.getElementById("SelectName").innerHTML = $(this).text();

 });

 document.getElementById("SelectName").innerHTML = "San Francisco";

Here's the code : http://jsfiddle.net/ub1g7fw6/


id's can only be used once on the page. You can do this by using a class instead:

HTML

<ul class="nav nav-pills">
   <li class="dropdown menu-btn">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown" >
         <span class="glyphicon glyphicon-map-marker"></span>
         <span class="update">San Francisco</span><b class="caret"></b>
      </a>
      <ul id="myCitylist" class="dropdown-menu">
        <li> <a href="#">San Jose</a> </li>
        <li> <a href="#">Silicon Valley</a> </li>
        <li> <a href="#">New York City</a> </li>
        <li> <a href="#">Paris</a> </li>
        <li> <a href="#">Silicon Valley</a> </li>
        <li> <a href="#">Tokyo</a> </li>
      </ul>
  </li>
</ul>

<div>Now we'll talk about <span class="update">San Francisco</span></div>

JS

$('.dropdown-menu').on('click', "li", function(){
  var optionChosen = $(this).text();
  $(this).closest("ul.nav.nav-pills").find("span.update").text(optionChosen).end().next().find("span.update").text(optionChosen);
 });

FIDDLE