1

I'm trying to figure out what I'm missing with the script below. My goal is to have an ordered list (per assignment requirements), where a pop up window with text comes up when any of the list items are clicked. Each list item would lead to different text.

I know there may be more efficient ways to do this, which are out of the scope of my understanding at this point, so I'm trying to do the following [non-working] work-around below.

Example: When the user clicks the "One" list item, a pop up window should appear with the text inside it saying "Item 1", but I get "undefined" as a result. Any tips?

My test HTML:

<ol id="javaList" onclick="popUp()">
    <li value="Item 1">One</li>
    <li value="Item 2">Two</li>
    <li value="Item 3">Three</li>
</ol>

The JavaScript:

<script>

    window.popUp = function() {
        var myWindow = window.open("", "", "width=400, height=200");
        var ls = document.getElementsByTagName("li");
        myWindow.document.write(ls.value);
    }

</script> 
CScottRun
  • 11
  • 2

2 Answers2

0

There are a couple of issues in your code.

You don't need to have the width and height in quotes, and you can capture the element with the event argument from your onclick handler. Your window.popup function should be:

<script>
window.popUp = function(event) {
    var myWindow = window.open("", "", 400, 200);
    var ls = event.currentTarget;
    myWindow.document.write(ls.value);
}
</script>
thealmightygrant
  • 701
  • 1
  • 5
  • 11
  • See my solution as well; you can't get a value of an `li`. So the last line should look something like `myWindow.document.write(ls.getAttribute('data-value'));` where the HTML is modified to replace `value` with `data-value`. – Sablefoste Feb 10 '17 at 04:42
0

You can't get the value of an li it returns 0 in every case. Try changing it to data-value instead.

If you are including the jQuery library, the solution becomes trivial. Your HTML would become:

<ol id="javaList">
    <li data-value="Item 1">One</li>
    <li data-value="Item 2">Two</li>
    <li data-value="Item 3">Three</li>
</ol>

And JavaScript would become:

$('li').on('click', function(event){
    var myWindow = window.open("", "", "width=400, height=200");
    myWindow.document.write($(this).data('value'));
}
Sablefoste
  • 4,032
  • 3
  • 37
  • 58