Тег OPTION, атрибут selected

:checked¶

Псевдокласс :checked находит любые элементы radio ( ), checkbox ( ) или option ( внутри ), которые выбраны или включены.

Пользователь может изменить это состояние, нажав на элемент, или выбрав другое значение, в этом случае :checked повторно не применится к элементу, а сохранится.

Синтаксис¶

/* Matches any checked/selected radio, checkbox, or option */ :checked  margin-left: 25px; border: 1px solid blue; > 

Спецификации¶

Описание и примеры¶

Пример 1¶

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
div> input type="radio" name="my-input" id="yes" /> label for="yes">Yeslabel> input type="radio" name="my-input" id="no" /> label for="yes">Nolabel> div> div> input type="checkbox" name="my-checkbox" id="opt-in" /> label for="opt-in">Check me!label> div> select name="my-select" id="fruit"> option value="opt1">Applesoption> option value="opt2">Grapesoption> option value="opt3">Pearsoption> select> 
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
div, select  margin: 8px; > /* Labels for checked inputs */ input:checked + label  color: red; > /* Radio element, when checked */ input[type='radio']:checked  box-shadow: 0 0 0 3px orange; > /* Checkbox element, when checked */ input[type='checkbox']:checked  box-shadow: 0 0 0 3px hotpink; > /* Option elements, when selected */ option:checked  box-shadow: 0 0 0 3px lime; color: red; > 

Пример 2: переключение элементов со скрытым флажком¶

В этом примере используется псевдо-класс :checked , чтобы пользователь мог переключать контент на основе состояния флажка, без использования JavaScript.

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
input type="checkbox" id="expand-toggle" /> table> thead> tr> th>Column #1th> th>Column #2th> th>Column #3th> tr> thead> tbody> tr class="expandable"> td>[more text]td> td>[more text]td> td>[more text]td> tr> tr> td>[cell text]td> td>[cell text]td> td>[cell text]td> tr> tr> td>[cell text]td> td>[cell text]td> td>[cell text]td> tr> tr class="expandable"> td>[more text]td> td>[more text]td> td>[more text]td> tr> tr class="expandable"> td>[more text]td> td>[more text]td> td>[more text]td> tr> tbody> table> label for="expand-toggle" id="expand-btn">Toggle hidden rowslabel> 
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
/* Hide the toggle checkbox */ #expand-toggle  display: none; > /* Hide expandable content by default */ .expandable  visibility: collapse; background: #ddd; > /* Style the button */ #expand-btn  display: inline-block; margin-top: 12px; padding: 5px 11px; background-color: #ff7; border: 1px solid; border-radius: 3px; > /* Show hidden content when the checkbox is checked */ #expand-toggle:checked ~ * .expandable  visibility: visible; > /* Style the button when the checkbox is checked */ #expand-toggle:checked ~ #expand-btn  background-color: #ccc; > 

Источник

Атрибут selected

Делает текущий пункт списка выделенным. Если у тега добавлен атрибут multiple , то можно выделять более одного пункта.

Синтаксис

Значения

Значение по умолчанию

По умолчанию этот атрибут выключен.

       

Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.

Типы тегов

HTML5

Блочные элементы

Строчные элементы

Универсальные элементы

Нестандартные теги

Осуждаемые теги

Видео

Документ

Звук

Изображения

Объекты

Скрипты

Списки

Ссылки

Таблицы

Текст

Форматирование

Формы

Фреймы

Источник

:checked

The user can engage this state by checking/selecting an element, or disengage it by unchecking/deselecting the element.

Note: Because browsers often treat s as replaced elements, the extent to which they can be styled with the :checked pseudo-class varies from browser to browser.

Syntax

Examples

Basic example

HTML

div> input type="radio" name="my-input" id="yes" value="yes" /> label for="yes">Yeslabel> input type="radio" name="my-input" id="no" value="no" /> label for="no">Nolabel> div> div> input type="checkbox" name="my-checkbox" id="opt-in" /> label for="opt-in">Check me!label> div> select name="my-select" id="fruit"> option value="opt1">Applesoption> option value="opt2">Grapesoption> option value="opt3">Pearsoption> select> 

CSS

div, select  margin: 8px; > /* Labels for checked inputs */ input:checked + label  color: red; > /* Radio element, when checked */ input[type="radio"]:checked  box-shadow: 0 0 0 3px orange; > /* Checkbox element, when checked */ input[type="checkbox"]:checked  box-shadow: 0 0 0 3px hotpink; > /* Option elements, when selected */ option:checked  box-shadow: 0 0 0 3px lime; color: red; > 

Result

Toggling elements with a hidden checkbox

This example utilizes the :checked pseudo-class to let the user toggle content based on the state of a checkbox, all without using JavaScript.

HTML

input type="checkbox" id="expand-toggle" /> table> thead> tr> th>Column #1th> th>Column #2th> th>Column #3th> tr> thead> tbody> tr class="expandable"> td>[more text]td> td>[more text]td> td>[more text]td> tr> tr> td>[cell text]td> td>[cell text]td> td>[cell text]td> tr> tr> td>[cell text]td> td>[cell text]td> td>[cell text]td> tr> tr class="expandable"> td>[more text]td> td>[more text]td> td>[more text]td> tr> tr class="expandable"> td>[more text]td> td>[more text]td> td>[more text]td> tr> tbody> table> label for="expand-toggle" id="expand-btn">Toggle hidden rowslabel> 

CSS

/* Hide the toggle checkbox */ #expand-toggle  display: none; > /* Hide expandable content by default */ .expandable  visibility: collapse; background: #ddd; > /* Style the button */ #expand-btn  display: inline-block; margin-top: 12px; padding: 5px 11px; background-color: #ff7; border: 1px solid; border-radius: 3px; > /* Show hidden content when the checkbox is checked */ #expand-toggle:checked ~ * .expandable  visibility: visible; > /* Style the button when the checkbox is checked */ #expand-toggle:checked ~ #expand-btn  background-color: #ccc; > 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

Источник

How to use Checkbox inside Select Option

The client has given me a design which has a Select Option menu containing a checkbox together with the item name as individual items in the list.Is there anyway possible to add a checkbox inside a Select Option menu?

NB: Developer needs to add his own id to make the menu effective, I only need the HTML CSS code if it is possible.

SOLUTION 1 :

You cannot place checkbox inside select element but you can get the same functionality by using HTML, CSS and JavaScript. Here is a possible working solution. The explanation follows.

enter image description here

Code:

var expanded = false;

function showCheckboxes() var checkboxes = document.getElementById("checkboxes");
if (!expanded) checkboxes.style.display = "block";
expanded = true;
> else checkboxes.style.display = "none";
expanded = false;
>
>
.multiselect width: 200px;
>

.selectBox position: relative;
>

.selectBox select width: 100%;
font-weight: bold;
>

.overSelect position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
>

#checkboxes display: none;
border: 1px #dadada solid;
>

#checkboxes label display: block;
>

#checkboxes label:hover background-color: #1e90ff;
>












SOLUTION 2 :

The best plugin so far is Bootstrap Multiselect





































SOLUTION 3 :

For a Pure CSS approach, you can use the [IKI_CODE] selector combined with the [IKI_CODE] selector to inline conditional content.

Just add the class :checked to your ::before element and include the following CSS:

You can use plain old unicode characters (with an escaped hex encoding) like these:

  • ☐ Ballot Box — select
  • ☑ Ballot Box With Check — .select-checkbox option::before content: «\2610»;
    width: 1.3em;
    text-align: center;
    display: inline-block;
    >
    .select-checkbox option:checked::before content: «\2611»;
    >

Or if you want to spice things up, you can use these FontAwesome glyphs

  • .fa-square-o.fa-square-o — \2610
  • .fa-check-square-o.fa-check-square-o — \2611

Screenshot

Demo in jsFiddle & Stack Snippets

SOLUTION 4 :

Try multiple-select. Looks to be much clean and managed solution, with tons of examples.

SOLUTION 5 :

for initiating the selectbox use this

 $("#selectBoxId").multiselect().multiselectfilter();

and when you have the data ready in json (from ajax or any method), first parse the data & then assign the js array to it

 var js_arr = $.parseJSON(/*data from ajax*/); 
$("#selectBoxId").val(js_arr);
$("#selectBoxId").multiselect("refresh");

SOLUTION 6 :

Use this code for checkbox list on option menu.

select width: 150px;
>

.select-checkbox option::before content: "\2610";
width: 1.3em;
text-align: center;
display: inline-block;
>
.select-checkbox option:checked::before content: "\2611";
>

.select-checkbox-fa option::before font-family: FontAwesome;
content: "\f096";
width: 1.3em;
display: inline-block;
margin-left: 2px;
>
.select-checkbox-fa option:checked::before content: "\f046";
>


Unicode




Font Awesome


SOLUTION 7 :

You might be loading multiselect.js file before the option list updated with AJAX call so while execution of multiselect.js file there is empty option list is there to apply multiselect functionlaity. So first update the option list by AJAX call then initiate the multiselect call you will get the dropdown list with the dynamic option list.

Hope this will help you out.

.dropdown-menu input margin-right: 10px;
>

SOLUTION 8 :

// This function should be called while loading page
var loadParentTaskList = function() $.ajax( url: yoururl,
method: 'POST',
success: function(data) // To add options list coming from AJAX call multiselect
for (var field in data) $('').appendTo('#parent_task');
>

// To initiate the multiselect call
$("#parent_task").multiselect( includeSelectAllOption: true
>)
>
>);
>
// Multiselect drop down list with id parent_task
var expanded = false;

function showCheckboxes() var checkboxes = document.getElementById("checkboxes");
if (!expanded) checkboxes.style.display = "block";
expanded = true;
> else checkboxes.style.display = "none";
expanded = false;
>
>

SOLUTION 9 :

I started from @vitfo answer but I want to have .multiselect width: 200px;
>

.selectBox position: relative;
>

.selectBox select width: 100%;
font-weight: bold;
>

.overSelect position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
>

#checkboxes display: none;
border: 1px #dadada solid;
>

#checkboxes label display: block;
>

$(".multiple_select").on('click', function(e) if (e.target.tagName == "OPTION") 
return; //don't close dropdown if i select option
>
$(this).toggleClass('multiple_select_active'); //close dropdown if click inside box
>);
$(".multiple_select").on('blur', function(e) $(this).removeClass('multiple_select_active'); //close dropdown if click outside
>);

$('.multiple_select option').mousedown(function(e) < //no ctrl to select multiple
e.preventDefault();
$(this).prop('selected', $(this).prop('selected') ? false : true); //set selected options on click
$(this).parent().change(); //trigger change event
>);


$("#myFilter").on('change', function() //here I get all options using $("#myFilter").val();
>);

Источник

Читайте также:  Сбросить все стили кнопки css
Оцените статью