简体   繁体   中英

altering the selected value from bootstrap dropdown menu via Vanilla Javascript

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM