Get checkbox value in jQuery

Jak mogę uzyskać wartość checkboxa w jQuery?

Author: Joel Beckham, 2010-05-14

14 answers

Aby uzyskać wartość atrybutu Value możesz zrobić coś takiego:

$("input[type='checkbox']").val();

Lub jeśli ustawiłeś dla niego class lub id, możesz:

$('#check_id').val();
$('.check_class').val();

Jednak zwróci to tę samą wartość niezależnie od tego, czy jest sprawdzona, czy nie, może to być mylące, ponieważ różni się od zachowania przesyłanego formularza.

Aby sprawdzić, czy jest sprawdzony, czy nie, wykonaj:

if ($('#check_id').is(":checked"))
{
  // it is checked
}
 757
Author: Sarfraz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-02 10:20:06

Te dwa sposoby działają:

  • $('#checkbox').prop('checked')
  • $('#checkbox').is(':checked') (thanks @mgsloan)

$('#test').click(function() {
    alert("Checkbox state (method 1) = " + $('#test').prop('checked'));
    alert("Checkbox state (method 2) = " + $('#test').is(':checked'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Check me: <input id="test" type="checkbox" />
 166
Author: Alain Tiemblo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-01 22:21:56

Spróbuj tego małego rozwiązania:

$("#some_id").attr("checked") ? 1 : 0;

Lub

$("#some_id").attr("checked") || 0;
 51
Author: RDK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-10 09:44:17

Tylko poprawne sposoby pobierania wartości pola wyboru są następujące

if ( elem.checked ) 
if ( $( elem ).prop( "checked" ) ) 
if ( $( elem ).is( ":checked" ) ) 

Jak wyjaśniono w oficjalnych dokumentach na stronie jQuery. Reszta metod nie ma nic wspólnego z właściwością pola wyboru, sprawdzają atrybut, co oznacza, że testują początkowy stan pola wyboru podczas ładowania. W skrócie:

  • Gdy masz element i wiesz, że jest to pole wyboru, możesz po prostu odczytać jego właściwość i nie potrzebujesz do tego jQuery (np. elem.checked) lub możesz użyć $(elem).prop("checked"), jeśli chcesz polegać na jQuery.
  • jeśli musisz znać (lub porównać) wartość przy pierwszym załadowaniu elementu (tj. wartość domyślną), poprawnym sposobem jest $(elem).is(":checked").

Odpowiedzi są mylące, proszę sprawdzić poniżej:

Http://api.jquery.com/prop/

 23
Author: Reza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-04 07:07:44

Tak dla wyjaśnienia:

$('#checkbox_ID').is(":checked")

Zwróci "prawda" lub "FAŁSZ"

 13
Author: Greg A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-26 21:10:01
$('#checkbox_id').val();
$('#checkbox_id').is(":checked");
$('#checkbox_id:checked').val();
 11
Author: Nalan Madheswaran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-15 01:25:45
jQuery(".checkboxClass").click(function(){
        var selectedCountry = new Array();
        var n = jQuery(".checkboxClass:checked").length;
        if (n > 0){
            jQuery(".checkboxClass:checked").each(function(){
                selectedCountry.push($(this).val());
            });
        }
        alert(selectedCountry);
    });
 9
Author: Jaskaran singh Rajal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-09 09:46:51

Proste, ale skuteczne i zakłada, że wiesz, że pole wyboru zostanie znalezione:

$("#some_id")[0].checked;

Daje true/false

 7
Author: Kevin Shea,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-06 10:36:08

Pomimo faktu, że to pytanie prosi o rozwiązanie jQuery, tutaj jest czysta odpowiedź JavaScript, ponieważ nikt nie wspomniał o nim.

BEZ jQuery:

Po prostu wybierz element i uzyskaj dostęp do checked właściwość (która zwraca wartość logiczną).

var checkbox = document.querySelector('input[type="checkbox"]');

alert(checkbox.checked);
<input type="checkbox"/>

Oto krótki przykład odsłuchania zdarzenia change:

var checkbox = document.querySelector('input[type="checkbox"]');
checkbox.addEventListener('change', function (e) {
    alert(this.checked);
});
<input type="checkbox"/>

Aby wybrać zaznaczone elementy, użyj :checked pseudo Klasa (input[type="checkbox"]:checked).

Oto przykład, który powtarza elementy sprawdzone input i zwraca mapowaną tablicę nazw sprawdzonego elementu.

Przykład Tutaj

var elements = document.querySelectorAll('input[type="checkbox"]:checked');
var checkedElements = Array.prototype.map.call(elements, function (el, i) {
    return el.name;
});

console.log(checkedElements);

var elements = document.querySelectorAll('input[type="checkbox"]:checked');
var checkedElements = Array.prototype.map.call(elements, function (el, i) {
    return el.name;
});

console.log(checkedElements);
<div class="parent">
    <input type="checkbox" name="name1" />
    <input type="checkbox" name="name2" />
    <input type="checkbox" name="name3" checked="checked" />
    <input type="checkbox" name="name4" checked="checked" />
    <input type="checkbox" name="name5" />
</div>
 6
Author: Josh Crozier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-15 04:37:28
//By each()
var testval = [];
 $('.hobbies_class:checked').each(function() {
   testval.push($(this).val());
 });


//by map()
var testval = $('input:checkbox:checked.hobbies_class').map(function(){
return this.value; }).get().join(",");

 //HTML Code

 <input type="checkbox" value="cricket" name="hobbies[]"  class="hobbies_class">Cricket 
  <input type="checkbox" value="hockey" name="hobbies[]" class="hobbies_class">Hockey

przykład
Demo

 5
Author: Kamal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-19 10:06:19

Oto jak uzyskać wartość wszystkich zaznaczonych checkboxów jako tablicę:

var values = (function() {
                var a = [];
                $(".checkboxes:checked").each(function() {
                    a.push(this.value);
                });
                return a;
            })()
 1
Author: Faraz Kelhini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-05 14:35:13
<script type="text/javascript">
$(document).ready(function(){
    $('.laravel').click(function(){
        var val = $(this).is(":checked");
        $('#category').submit();
    });
});

<form action="{{route('directory')}}" method="post" id="category">
                        <input type="hidden" name="_token" value="{{ csrf_token() }}">
                        <input name="category" value="{{$name->id}}"  class="laravel" type="checkbox">{{$name->name}}
                      </form>
 1
Author: Kuldeep Mishra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-07 06:34:19

Użyj Tego $('input [name^=CheckBoxInput]').val ();

 1
Author: Myint Thu Lwin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-25 10:33:05

$('.class[value=3]").prop ('checked', true);

 1
Author: Jacksonit.org,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-07 09:57:09