Home > Web Front-end > HTML Tutorial > Perfectly solves the problem that the select option in HTML cannot be hidden.

Perfectly solves the problem that the select option in HTML cannot be hidden.

高洛峰
Release: 2017-02-15 14:07:55
Original
7208 people have browsed it

I encountered this problem accidentally during the development process, and the first time to solve the problem was Baidu. The results are as follows:

1. The solution of setting display:none of option first is definitely not feasible;
2. Two solutions proposed by a netizen:
a. On the option tag Adding the disabled="disabled" attribute indicates that it is unavailable. This solution only makes the option unselectable, but does not hide it
b. If you want to hide it, you can only remove the option from the DOM tree, and then modify the removed option The option is cached, and then the option is taken out of the cache and added to the DOM tree when it is to be displayed.
It is definitely not in line with the requirements.
c. The ultimate solution (tested to be compatible with all browsers): Add a parent tag to the option, and set the parent tag to hide [the span tag is used here]. If you want to display it, remove the parent tag. Can.

However, the above methods are of no use

Final solution:

//将select通过clone方法保存
var select= $("#select").clone();

//删除所有的option
$("#select").find('option').remove();

//查找出需要显示的option并复制
var options = select.find("option[value=1]").clone();

//将需要显示的option添加到select中
$("#select").append(options);

//因为option.remove()不会刷新控件,需要将新的option切换上去
//这里排除了options.size() == 0的情况
$("#select").find('option').eq(0).attr("selected",true);
Copy after login

That’s it.

More perfect solutions to the problem that the select option in HTML cannot be hidden. For related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template