问问题
106 次
1 回答
0
No, there is no way to enforce such a limit without the use of JavaScript. Something like this could work:
func = function(e) {
e|e=window.event;
var t = e.srcElement || e.target;
if( !t.tagName) t = t.parentNode;
if( t.tagName.toLowerCase() == "select" && t.hasAttribute("multiple") && t.hasAttribute("data-max")) {
var o = t.options, l = o.length, i, m = +t.getAttribute("data-max");
for( i=0; i<l; i++) {
if( o[i].selected) {
if(m>0) m--;
else o[i].selected = false;
}
}
}
};
if( document.body.addEventListener) document.body.addEventListener("change",func,false);
else document.body.attachEvent("onchange",func);
Then you can use this HTML:
<select multiple data-max="4">
Additionally, you should implement server-side validation. Assuming this HTML:
<select multiple name="test[]">
You could use this PHP:
$_POST['test'] = array_slice($_POST['test'],0,4); // adjust the 4 to whatever limit
于 2013-05-15T17:51:15.863 回答