0

I've just started learning Javascript, so looking for vanilla Javascript answer (not JQUERY);

I have created a dynamic drop-down menu via createDropdown function;

The menu contains button elements.

Whenever a user clicks on one of these dropdown buttons,

I want an alert popup with the value, (see the createChart function).

I have tried variations of dropDownMenu.selectedIndex but it's only alerting a "undefined" value.

var range = function (start, stop, step) {
    step = step || 1;
    var arr = [];
    for (var i = start; i < stop; i += step) {
        arr.push(Math.round((i + Number.EPSILON) * 100) / 100)
    }
    return arr;
};

function createDropDown() {

    var dropDown = document.querySelector('.btn[name="annual-gains"]');
    
    // <button class="dropdown-item" type="button">test</button>')

    dropDown.addEventListener("click", function (event) {
        console.log("querySelectorは合ってる")
        let values = range(0.05, 1.05, .05);


        for (var i = 0; i < values.length; i += 1) {
            let value = values[i]
            
            var myOption = document.createElement('button');
            // id
            myOption.type = 'button';
            // クラス名
            myOption.className = 'dropdown-item';
            // テキスト内容
            myOption.innerHTML = values[i];

            const dropDownMenu = document.querySelector('.dropdown-menu[name="test"]');
            dropDownMenu.appendChild(myOption);
        
        }
        createChart();
        event.preventDefault();
        

    })

}


function createChart() {

    
    const dropDownMenu = document.querySelector('.dropdown-menu[name="test"]');


    dropDownMenu.addEventListener("click", function (event) {
        let value = dropDownMenu.selectedIndex
        alert(value)
    
    })}
        
        
createDropDown()

EDIT (updated with html code):

The dropdown menu was taken from bootstrap: https://getbootstrap.com/docs/4.1/components/dropdowns/#menu-items

<div class="dropdown">
    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown"
      aria-haspopup="true" aria-expanded="false" name="annual-gains">
      Annual Gains
    </button>
    <div class="dropdown-menu" aria-labelledby="dropdownMenu2" name="test">
    </div>
  </div>
5
  • 1
    Just curious, why not jQuery? You're already using Bootstrap which has a hard dependency on jQuery Commented Dec 7, 2020 at 1:50
  • 1
    selectedIndex is for <select> elements with <options> but... 1) You haven't shown what type of element .dropdown-menu[name="test"] is, and 2) You are adding <button> elements to it, not <option> elements Commented Dec 7, 2020 at 1:56
  • wondering if you can use dropDownMenu.addEventListener("change" ... because click can be dispatching before select changes and not has a selected option yet. will try to reproduce... Commented Dec 7, 2020 at 1:57
  • @phil I haven't started learning jQuery, so wanted to stick with javascript first. Commented Dec 7, 2020 at 2:13
  • @Phil I've updated the dropdown-menu html in OP. Commented Dec 7, 2020 at 2:17

1 Answer 1

1

You can add an event listener to each button

myOption.addEventListener("click", (event) => event.target )  //event.target is the pressed button

here a working example: https://codepen.io/sarabadu/pen/YzGqgmY

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you.I'm looking at the codpen now. So you included the event-listener within the for-loop. Is the dataset portion also needed? I am using inner-html to populate the values. I wonder if dataset.values are also need to populate the values.
Dataset is only a nice way to save data on the elements you can render as data-foo and take it as dataset.foo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.