1

I have a list of links such as:

<li><a href="#">Alabama</a></li>
<li><a href="#">Alaska</a></li>
<li><a href="#">Arizona</a></li>
<li><a href="#">Arkansas</a></li>
<li><a href="#">California</a></li>

I have a div section(an article) that I want to update dynamically as a selection is made from the list.

<div>Select a state from the list</div>

Desired outcome: Selecting Alabama from the list displays in the main div a list of counties in Alabama.

Current outcome: Selecting Alabama from the list does not update the main div.

How can I best accomplish this? JavaScript? JQuery? JSFiddle?

I am looking for something maybe similar to this: Change the content of a div based on selection from dropdown menu

But I had no luck getting that to work with a list.

Community
  • 1
  • 1
Levi J
  • 97
  • 2
  • 15
  • 2
    can you post the code that you have tried? Did you try that example that you posted? – Adjit Dec 09 '16 at 22:00
  • Yeah, I gave the answer by rybo111 a try, but had a hard time converting it to work with a list selection. Particularly the 3rd line in his JQuery about option:selected. I am not familiar with JQuery. – Levi J Dec 09 '16 at 22:05
  • Were you getting any errors / properly incorporating jQuery into your page? – Adjit Dec 09 '16 at 22:07

3 Answers3

1

Try this:

<ul id="list">
<li><a href="#">Alabama</a></li>
<li><a href="#">Alaska</a></li>
<li><a href="#">Arizona</a></li>
<li><a href="#">Arkansas</a></li>
<li><a href="#">California</a></li>
</ul>
<div id="selection"></div>

jQuery:

$(document).ready(function() {
     $('#list a').on('click', function(e) {
       e.preventDefault();
       $('#selection').text($(this).text());
     });
});
Rafał R
  • 241
  • 2
  • 10
1

Try adding an event listener to listen to clicks on the unordered list element.

var states = document.getElementById('states');
var main = document.getElementById('main');

states.addEventListener('click', function(e) {
  e.preventDefault(); // don't navigate to <a> tag href
  if (e.target.tagName === 'A') {
    main.textContent = e.target.textContent;
  }
});
<ul id="states">
  <li><a href="#">Alabama</a></li>
  <li><a href="#">Alaska</a></li>
  <li><a href="#">Arizona</a></li>
  <li><a href="#">Arkansas</a></li>
  <li><a href="#">California</a></li>
</ul>


<div id="main">Main</div>

Note that we can add a single click event listener to the parent of all the list items and then we check to make sure the click was on an A tag by comparing the tagName. Then we can copy the textContent from the clicked element to the main element.

styfle
  • 22,361
  • 27
  • 86
  • 128
1

There are so many different ways to do this and dependent on what the deeper level contents are will determine best method.

If it is an external html page you could so something like

html

<div id="div2"><div>

jquery

 $('#div1').select(),
 $('#div2').load("statesName.html");
norcal johnny
  • 2,050
  • 2
  • 13
  • 17