开发者

JavaScript, HTML: How to tell if option box is has been set?

开发者 https://www.devze.com 2023-01-03 18:36 出处:网络
I am having trouble finding out how to figure out if an HTML dropdown box has been set? Ok, I understand how I can check the index once it has been activated and an ite开发者_StackOverflow中文版m chos

I am having trouble finding out how to figure out if an HTML dropdown box has been set?

Ok, I understand how I can check the index once it has been activated and an ite开发者_StackOverflow中文版m chosen. But, how do I determine that the box hasn't been touched and no item selected?

Thanks.


The select.options.selectedIndex will be -1 in that case.


I don't think there's a native method, but you can add an event listener to call a function when the select is changed:

function addEvent(elm, evType, fn, useCapture) {
    if (elm.addEventListener) {
        elm.addEventListener(evType, fn, useCapture);
        return true;
    }
    else if (elm.attachEvent) {
        var r = elm.attachEvent('on' + evType, fn);
        return r;
    }
    else {
        elm['on' + evType] = fn;
    }
}
hasBeenTouched = false;
addEvent(selectEl, 'change', function() {
    hasBeenTouched = true;
});


It sounds like you want to make sure a user has selected an option and not just submitted the form with the default option. This situation is commonly achieved by having a "label" option (sometimes blank to keep the size down) in your drop down box, that is selected by default, followed by validation checking to see if another option has been selected:

<select>
  <option>-- Please choose an option -- </option>
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
</select>

Using validation properly (both server-side and client-side), you're able to implement a solution that doesn't rely on Javascript to check if an option has been properly selected.


After the document is loaded (naively window.onload), manually set the drop-down list selectedIndex to -1 (as others have observed, the default is otherwise for the first item to be selected)

window.onload = function() {
    document.getElementById('ddlId').selectedIndex = -1;
};

There's no way for the user to set the drop-down list to unselected through the browser interface, so you can be sure it is both unset and untouched by testing whether the selectedIndex is still -1 at any point after initially setting it yourself.

0

精彩评论

暂无评论...
验证码 换一张
取 消