jQuery prevent change for select

前端 未结 13 1375
無奈伤痛
無奈伤痛 2020-11-28 10:51

I want to prevent a select box from being changed if a certain condition applies. Doing this doesn\'t seem to work:

$(\'#my_select\').bind(\'change\', funct         


        
13条回答
  •  臣服心动
    2020-11-28 11:43

    I was looking for "javascript prevent select change" on Google and this question comes at first result. At the end my solution was:

    const $select = document.querySelector("#your_select_id");
    let lastSelectedIndex = $select.selectedIndex;
    // We save the last selected index on click
    $select.addEventListener("click", function () {
        lastSelectedIndex = $select.selectedIndex;
    });
    
    // And then, in the change, we select it if the user does not confirm
    $select.addEventListener("change", function (e) {
        if (!confirm("Some question or action")) {
            $select.selectedIndex = lastSelectedIndex;
            return;
        }
        // Here do whatever you want; the user has clicked "Yes" on the confirm
        // ...
    });
    

    I hope it helps to someone who is looking for this and does not have jQuery :)

提交回复
热议问题