Selektors checked

Selektors :checked atlasa elementus, kas ir izvēlēti, tas ir, tos, kuriem ir atribūti checked vai selected. Selektors :checked strādā ar izvēles rūtiņām (checkbox) un radio pogām (radio), kā arī elementiem ar tagu option. Lai iegūtu tikai izvēlētās opcijas elementiem select, izmanto selektoru selected.

Sintakse

Tā mēs atlasām elementus ar atribūtu checked:

javascript$(':checked');

Piemērs

Katru reizi, kad tiek atlasīta izvēles rūtiņa, parādīsim atzīmēto izvēles rūtiņu skaitu. Kā jūs redzat pirms pirmā klikšķa tiks parādītas izvēles rūtiņas, kas ir atlasītas pēc noklusējuma, tā ir otrā un ceturtā:

html<form>
<p>
  <input type="checkbox" name="cbox" value="one">
  <input type="checkbox" name="cbox" value="two" checked="checked">
  <input type="checkbox" name="cbox" value="three">
  <input type="checkbox" name="cbox" value="four" checked>
  <input type="checkbox" name="cbox" value="five">
</p>
</form>
<div></div>
cssdiv {
  color: green;
}
javascriptlet countChecked = function() {
  let n = $('input:checked').length;
  $('div').text('Atzīmētie: ' + n);
};
countChecked();

$('input[type=checkbox]').on('click', countChecked);

Piemērs

Klikšķa brīdī parādīsim apakšā katras izvēlētās radio pogas vērtību:

html<form>
  <div>
    <input type="radio" name="digits" value="one" id="one">
    <label for="one">one</label>
  </div>
  <div>
    <input type="radio" name="digits" value="two" id="two">
    <label for="two">two</label>
  </div>
  <div>
    <input type="radio" name="digits" value="three" id="three">
    <label for="three">three</label>
  </div>
  <div id="text"></div>
</form>
cssinput, label {
  line-height: 1.5em;
}
javascript$('input').on('click', function() {
  $('#text').html($('input:checked').val() + ' ir atzīmēts!');
});

Skatiet arī