onclick event in disabled element Javascript [duplicate]

天涯浪子 提交于 2021-02-08 09:10:28

问题


I'm developing an uniform store and in the detail page, the user has to select the model before he/she selects the size. Until he/she selects the model, the size select box is disabled. What I would like to have is, even when the size box is disabled and the user tries to click it before selecting the model, the model box becomes red.

I tried using onclick event, but, when the box is disabled, it doesn't do anything. (I'm using SAPUI5 on this website too, I don't think this is any problem). Only as a test, I made this:

oSelectTamanho = new sap.m.Select();
oSelectTamanho.onclick = function() {
    console.log("click");
}

As I mentioned, it only outputs the "click" when the box is enabled, and I would need this when the box is disabled.

Do you have any idea how can I achieve this?

Thank you.

Eva.


回答1:


As you see, disabled elements do not produce events. Using an overlay element is one possible solution. Example using an overlay div.

CSS

#wrapper {
    display:inline-block;
    position:relative;
}
#overlay {
    display:none;
    width:100%;
    height:100%;
    position:absolute;
    top:0
    left:0;
    bottom:0;
    right:0;
}
#cars:disabled + #overlay {
    display:block;
}

HTML

<button id="button">Enable</button>
<div id="wrapper">
    <select id="cars" disabled>
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
    </select>
    <div id="overlay"></div>
</div>

Javascript

var button = document.getElementById('button'),
    cars = document.getElementById('cars'),
    overlay = document.getElementById('overlay');

button.addEventListener('click', function () {
    cars.disabled = !cars.disabled;
    if (cars.disabled) {
        button.textContent = 'Enable';
    } else {
        button.textContent = 'Disable';
    }
}, true);

cars.addEventListener('change', function (evt) {
    console.log(evt.target.value);
}, true);

overlay.addEventListener('click', function () {
    alert('Disabled');
}, true);

On jsFiddle



来源:https://stackoverflow.com/questions/24822097/onclick-event-in-disabled-element-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!