简体   繁体   English

在 jQuery 中如何检查复选框是否被选中?

[英]How do I check whether a checkbox is checked in jQuery?

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.我需要检查复选框的checked属性,并使用 jQuery 根据选中的属性执行操作。

For example, if the age checkbox is checked, then I need to show a textbox to enter age , else hide the textbox.例如,如果选中了age复选框,那么我需要显示一个文本框来输入age ,否则隐藏该文本框。

But the following code returns false by default:但是下面的代码默认返回false

 if ($('#isAgeSelected').attr('checked')) { $("#txtAge").show(); } else { $("#txtAge").hide(); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" id="isAgeSelected"/> <div id="txtAge" style="display:none"> Age is selected </div>

How do I successfully query the checked property?如何成功查询到已checked的属性?

How do I successfully query the checked property?如何成功查询checked属性?

The checked property of a checkbox DOM element will give you the checked state of the element.复选框 DOM 元素的checked属性将为您提供元素的checked状态。

Given your existing code, you could therefore do this:鉴于您现有的代码,您可以这样做:

if(document.getElementById('isAgeSelected').checked) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}

However, there's a much prettier way to do this, using toggle :然而,有一种更漂亮的方法来做到这一点,使用toggle

 $('#isAgeSelected').click(function() { $("#txtAge").toggle(this.checked); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" id="isAgeSelected"/> <div id="txtAge" style="display:none">Age is something</div>

Use jQuery's is() function:使用 jQuery 的is()函数:

if($("#isAgeSelected").is(':checked'))
    $("#txtAge").show();  // checked
else
    $("#txtAge").hide();  // unchecked

Using jQuery > 1.6使用 jQuery > 1.6

<input type="checkbox" value="1" name="checkMeOut" id="checkMeOut" checked="checked" />

// traditional attr
$('#checkMeOut').attr('checked'); // "checked"
// new property method
$('#checkMeOut').prop('checked'); // true

Using the new property method:使用新的属性方法:

if($('#checkMeOut').prop('checked')) {
    // something when checked
} else {
    // something else when not
}

jQuery 1.6+ jQuery 1.6+

$('#isAgeSelected').prop('checked')

jQuery 1.5 and below jQuery 1.5 及以下

$('#isAgeSelected').attr('checked')

Any version of jQuery任何版本的 jQuery

// Assuming an event handler on a checkbox
if (this.checked)

All credit goes to Xian .所有功劳都归功于西安

I am using this and this is working absolutely fine:我正在使用这个,这工作得很好:

$("#checkkBoxId").attr("checked") ? alert("Checked") : alert("Unchecked");

Note: If the checkbox is checked it will return true otherwise undefined, so better check for the "TRUE" value.注意:如果复选框被选中,它将返回真否则未定义,所以最好检查“真”值。

Use:用:

<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned

$("#planned_checked").change(function() {
    if($(this).prop('checked')) {
        alert("Checked Box Selected");
    } else {
        alert("Checked Box deselect");
    }
});

 $("#planned_checked").change(function() { if($(this).prop('checked')) { alert("Checked Box Selected"); } else { alert("Checked Box deselect"); } });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned

Since jQuery 1.6, the behavior of jQuery.attr() has changed and users are encouraged not to use it to retrieve an element's checked state.从 jQuery 1.6 开始, jQuery.attr()的行为发生了变化,鼓励用户不要使用它来检索元素的选中状态。 Instead, you should use jQuery.prop() :相反,您应该使用jQuery.prop()

$("#txtAge").toggle(
    $("#isAgeSelected").prop("checked") // For checked attribute it returns true/false;
                                        // Return value changes with checkbox state
);

Two other possibilities are:另外两种可能性是:

$("#txtAge").get(0).checked
$("#txtAge").is(":checked")

This worked for me:这对我有用:

$get("isAgeSelected ").checked == true

Where isAgeSelected is the id of the control.其中isAgeSelected是控件的 id。

Also, @karim79's answer works fine.另外,@karim79 的回答工作正常。 I am not sure what I missed at the time I tested it.我不确定在测试时我错过了什么。

Note, this is answer uses Microsoft Ajax, not jQuery请注意,这是使用 Microsoft Ajax 而不是 jQuery 的答案

If you are using an updated version of jquery, you must go for .prop method to resolve your issue:如果您使用的是 jquery 的更新版本,则必须使用.prop方法来解决您的问题:

$('#isAgeSelected').prop('checked') will return true if checked and false if unchecked. $('#isAgeSelected').prop('checked')将在选中时返回true ,如果未选中则返回false I confirmed it and I came across this issue earlier.我确认了这一点,并且我早些时候遇到了这个问题。 $('#isAgeSelected').attr('checked') and $('#isAgeSelected').is('checked') is returning undefined which is not a worthy answer for the situation. $('#isAgeSelected').attr('checked')$('#isAgeSelected').is('checked')返回undefined这对于这种情况来说不是一个有价值的答案。 So do as given below.因此,请按照下面的说明进行操作。

if($('#isAgeSelected').prop('checked')) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}

Hope it helps :)- Thanks.希望它有帮助:)-谢谢。

Use:用:

<input type="checkbox" id="abc" value="UDB">UDB
<input type="checkbox" id="abc" value="Prasad">Prasad
$('input#abc').click(function(){
  if($(this).is(':checked'))
  {
    var checkedOne=$(this).val()
    alert(checkedOne);

    // Do some other action
  }
})

This can help if you want that the required action has to be done only when you check the box not at the time you remove the check.如果您希望仅在选中复选框而不是在取消选中时才执行所需的操作,这会有所帮助。

Using the Click event handler for the checkbox property is unreliable, as the checked property can change during the execution of the event handler itself!对 checkbox 属性使用Click事件处理程序是不可靠的,因为在事件处理程序本身的执行过程中, checked属性可能会发生变化!

Ideally, you'd want to put your code into a change event handler such as it is fired every time the value of the check box is changed (independent of how it's done so).理想情况下,你会希望把你的代码放到一个change的事件处理程序,例如它被激发每个复选框的值发生改变时(独立于它是如何做的话)。

$('#isAgeSelected').bind('change', function () {

   if ($(this).is(':checked'))
     $("#txtAge").show();
   else
     $("#txtAge").hide();
});

I decided to post an answer on how to do that exact same thing without jQuery.我决定发布一个关于如何在没有 jQuery 的情况下做完全相同的事情的答案。 Just because I'm a rebel.只因为我是个叛逆者。

var ageCheckbox = document.getElementById('isAgeSelected');
var ageInput = document.getElementById('txtAge');

// Just because of IE <333
ageCheckbox.onchange = function() {
    // Check if the checkbox is checked, and show/hide the text field.
    ageInput.hidden = this.checked ? false : true;
};

First you get both elements by their ID.首先,您通过 ID 获取这两个元素。 Then you assign the checkboxe's onchange event a function that checks whether the checkbox got checked and sets the hidden property of the age text field appropriately.然后为复选框的onchange事件分配一个函数,该函数检查复选框是否被选中并适当地设置年龄文本字段的hidden属性。 In that example using the ternary operator.在那个使用三元运算符的例子中。

Here is a fiddle for you to test it.这是一个小提琴供您测试。

Addendum附录

If cross-browser compatibility is an issue then I propose to set the CSS display property to none and inline .如果跨浏览器兼容性是一个问题,那么我建议将 CSS display属性设置为noneinline

elem.style.display = this.checked ? 'inline' : 'none';

Slower but cross-browser compatible.较慢但跨浏览器兼容。

I believe you could do this:我相信你可以这样做:

if ($('#isAgeSelected :checked').size() > 0)
{
    $("#txtAge").show(); 
} else { 
    $("#txtAge").hide();
}

I ran in to the exact same issue.我遇到了完全相同的问题。 I have an ASP.NET checkbox我有一个 ASP.NET 复选框

<asp:CheckBox ID="chkBox1" CssClass='cssChkBox1' runat="server" />

In the jQuery code I used the following selector to check if the checkbox was checked or not, and it seems to work like a charm.在 jQuery 代码中,我使用以下选择器来检查复选框是否被选中,它似乎很有魅力。

if ($("'.cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }

I'm sure you can also use the ID instead of the CssClass,我确定您也可以使用 ID 而不是 CssClass,

if ($("'#cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }

I hope this helps you.我希望这可以帮助你。

You can try the change event of checkbox to track the :checked state change.您可以尝试使用 checkbox 的change事件来跟踪:checked状态更改。

 $("#isAgeSelected").on('change', function() { if ($("#isAgeSelected").is(':checked')) alert("checked"); else { alert("unchecked"); } });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" id="isAgeSelected" /> <div id="txtAge" style="display:none"> Age is selected </div>

This code will help you此代码将帮助您

$('#isAgeSelected').click(function(){
   console.log(this.checked);
   if(this.checked == true) {
        $("#txtAge").show();
    } else {
       $("#txtAge").hide();
   }
});

There are many ways to check if a checkbox is checked or not:有很多方法可以检查复选框是否被选中:

Way to check using jQuery使用 jQuery 检查的方法

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

Check example or also document:检查示例或文档:

This works for me:这对我有用:

/* isAgeSelected being id for checkbox */

$("#isAgeSelected").click(function(){
  $(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
});

This is some different method to do the same thing:这是做同一件事的一些不同方法:

 $(document).ready(function (){ $('#isAgeSelected').click(function() { // $("#txtAge").toggle(this.checked); // Using a pure CSS selector if ($(this.checked)) { alert('on check 1'); }; // Using jQuery's is() method if ($(this).is(':checked')) { alert('on checked 2'); }; // // Using jQuery's filter() method if ($(this).filter(':checked')) { alert('on checked 3'); }; }); });
 <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <input type="checkbox" id="isAgeSelected"/> <div id="txtAge" style="display:none">Age is something</div>

Use this:用这个:

if ($('input[name="salary_in.Basic"]:checked').length > 0)

The length is greater than zero if the checkbox is checked.如果选中该复选框,则长度大于零。

My way of doing this is:我这样做的方法是:

if ( $("#checkbox:checked").length ) {       
    alert("checkbox is checked");
} else {
    alert("checkbox is not checked");
}
$(selector).attr('checked') !== undefined

如果输入被检查,则返回true否则返回false

$(document).ready(function() {    
    $('#agecheckbox').click(function() {
        if($(this).is(":checked"))
        {
            $('#agetextbox').show();
        } else {
            $('#agetextbox').hide();
        }
    });
});

You can use:您可以使用:

  if(document.getElementById('isAgeSelected').checked)
    $("#txtAge").show();  
  else
    $("#txtAge").hide();

if($("#isAgeSelected").is(':checked'))
  $("#txtAge").show();  
else
  $("#txtAge").hide();

Both of them should work.他们两个都应该工作。

1) If your HTML markup is: 1) 如果您的 HTML 标记是:

<input type="checkbox"  />

attr used:使用的属性:

$(element).attr("checked"); // Will give you undefined as initial value of checkbox is not set

If prop is used:如果使用道具:

$(element).prop("checked"); // Will give you false whether or not initial value is set

2) If your HTML markup is: 2) 如果您的 HTML 标记是:

 <input type="checkbox"  checked="checked" />// May be like this also  checked="true"

attr used:使用的属性:

$(element).attr("checked") // Will return checked whether it is checked="true"

Prop used:道具使用:

$(element).prop("checked") // Will return true whether checked="checked"

The top answer didn't do it for me.最佳答案对我不起作用。 This did though:虽然这样做了:

<script type="text/javascript">
    $(document).ready(function(){

        $("#li_13").click(function(){
            if($("#agree").attr('checked')){
                $("#saveForm").fadeIn();
            }
            else
            {
                $("#saveForm").fadeOut();
            }
        });
    });
</script>

Basically when the element #li_13 is clicked, it checks if the element # agree (which is the checkbox) is checked by using the .attr('checked') function.基本上,当元素 #li_13 被点击时,它会检查是否使用.attr('checked')函数检查了元素 #同意(这是复选框)。 If it is then fadeIn the #saveForm element, and if not fadeOut the saveForm element.如果是,则在#saveForm 元素中淡入淡出,如果不是在saveForm 元素中淡出。

This example is for button.这个例子是按钮。

Try the following:请尝试以下操作:

<input type="button" class="check" id="checkall" value="Check All" />  &nbsp; <input type="button" id="remove" value="Delete" /> <br/>

<input type="checkbox" class="cb-element"  value="1" /> Checkbox  1 <br/>
<input type="checkbox" class="cb-element"  value="2" /> Checkbox  2 <br/>
<input type="checkbox" class="cb-element"  value="3" /> Checkbox  3 <br/>


$('#remove').attr('disabled', 'disabled'); 

$(document).ready(function() {  

    $('.cb-element').click(function() {

        if($(this).prop('checked'))
        {
            $('#remove').attr('disabled', false);
        }
        else
        {
            $('#remove').attr('disabled', true);
        }
    });   

    $('.check:button').click(function()
{
    var checked = !$(this).data('checked');
    $('input:checkbox').prop('checked', checked);
    $(this).data('checked', checked);

    if(checked == true)
    {
        $(this).val('Uncheck All');
         $('#remove').attr('disabled', false);
    }

    else if(checked == false)
    {
        $(this).val('Check All');
        $('#remove').attr('disabled', true);
    }
});
});

To act on a checkbox being checked or unchecked on click.对单击时选中或取消选中的复选框进行操作。

 $('#customCheck1').click(function() { if (this.checked) { console.log('checked'); } else { console.log('un-checked'); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" id="customCheck1">

EDIT: Not a nice programming expression if (boolean == true) though .checked property might return other type variables as well..编辑:不是一个很好的编程表达式if (boolean == true)虽然.checked属性也可能返回其他类型变量..

It is better to use .prop("checked") instead.最好改用.prop("checked") It returns true and false only.它只返回truefalse

I am using this:我正在使用这个:

 <input type="checkbox" id="isAgeSelected" value="1" /> <br/>
 <input type="textbox" id="txtAge" />

 $("#isAgeSelected").is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();

Though you have proposed a JavaScript solution for your problem (displaying a textbox when a checkbox is checked ), this problem could be solved just by css .虽然你已经提出了一个JavaScript解决方案为您的问题(显示textbox时, checkboxchecked ),这个问题可能只是CSS来解决。 With this approach, your form works for users who have disabled JavaScript.使用这种方法,您的表单适用于禁用 JavaScript 的用户。

Assuming that you have the following HTML:假设您有以下 HTML:

<label for="show_textbox">Show Textbox</label>
<input id="show_textbox" type="checkbox" />
<input type="text" />

You can use the following CSS to achieve the desired functionality:您可以使用以下 CSS 来实现所需的功能:

 #show_textbox:not(:checked) + input[type=text] {display:none;}

For other scenarios, you may think of appropriate CSS selectors.对于其他场景,您可能会想到合适的 CSS 选择器。

Here is a Fiddle to demonstrate this approach .这里有一个 Fiddle 来演示这种方法

Toggle: 0/1 or else切换:0/1 或其他

<input type="checkbox" id="nolunch" />
<input id="checklunch />"

    $('#nolunch').change(function () {
    if ($(this).is(':checked')) {
        $('#checklunch').val('1');
    };
    if ($(this).is(':checked') == false) {
        $('#checklunch').val('0');
    };
});

Please try below code to check checkbox is checked or not请尝试下面的代码来检查复选框是否被选中

$(document).ready(function(){

    $("#isAgeSelected").on('change',function(){

    if($("#isAgeSelected").is(':checked'))
        $("#txtAge").show();  // checked
    else{
        $("#txtAge").hide();  // unchecked
    }

   });

});

I'm sure it's not some revelation, but I didn't see it all in one example:我敢肯定这不是什么启示,但我并没有在一个例子中看到这一切:

Selector for all checked checkboxes(on the page):所有选中复选框的选择器(在页面上):

$('input[type=checkbox]:checked')

I verified in Firefox 9.0.1 that the following works for catching the state of a checkbox post change:我在 Firefox 9.0.1 中验证了以下方法可用于捕获复选框后更改的状态:

$("#mycheckbox").change(function() {
    var value = $(this).prop("checked") ? 'true' : 'false';                     
    alert(value);
});

I think it will be the simple one 我认为这将是简单的

$('#isAgeSelected').change(function() {
    if($(this).is(":checked")) {
        $('#txtAge').show();
    }
else{
        $('#txtAge').hide();
    }                                          
});

Include jQuery from the local file system.从本地文件系统中包含 jQuery。 I used Google's CDN , and there are also many CDNs to choose from.我用的是谷歌的CDN ,也有很多CDN可以选择。

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

The code will execute as soon as a checkbox inside mycheck class is clicked.单击mycheck类中的复选框后,代码将立即执行。 If the current clicked checkbox is checked then it will disable all others and enable the current one.如果选中当前单击的复选框,则它将禁用所有其他复选框并启用当前复选框。 If the current one is unchecked, it will again enable all checkboxes for rechecking.如果当前未选中,它将再次启用所有复选框以重新选中。

<script type="text/javascript">
    $(document).ready(function() {

        var checkbox_selector = '.mycheck input[type=checkbox]';

        $(checkbox_selector).click(function() {
            if ($($(this)).is(':checked')) {

                // Disable all checkboxes
                $(checkbox_selector).attr('disabled', 'disabled');

                // Enable current one
                $($(this)).removeAttr('disabled');
            }
            else {
                // If unchecked open all checkbox
                $(checkbox_selector).removeAttr('disabled');
            }
        });
    });
</script>

Simple form to test简单的形式来测试

<form method="post" action="">
    <div class="mycheck">
        <input type="checkbox" value="1" /> Television
        <input type="checkbox" value="2" /> Computer
        <input type="checkbox" value="3" /> Laptop
        <input type="checkbox" value="4" /> Camera
        <input type="checkbox" value="5" /> Music Systems
    </div>
</form>

Output screen:输出画面:

在此处输入图像描述

if($("#checkkBoxId").is(':checked')){
  alert("Checked=true");
}

or要么

if($("#checkkBoxId").attr('checked') == true){
  alert("checked=true");
}

The checked attribute of an input type="checkbox" is mapped with the defaultChecked property, not with the checked property. input type="checkbox"checked属性映射到defaultChecked属性,而不是checked属性。

So when doing something in a page when a checkbox is checked on uncheked, use the prop() method instead.因此,当一个复选框被取消选中时在页面中执行某些操作时,请改用prop()方法。 It fetches the property value and changes as the state of the checkbox changes.它获取属性值并随着复选框状态的变化而变化。

Using attr( ) or getAttribute (in pure JavaScript) in these cases are not the proper way of doing things.在这些情况下使用attr( ) 或getAttribute (在纯 JavaScript 中)并不是正确的处理方式。

if elem is the concerned checkbox then do something like this to fetch the value:如果elem是相关的复选框,那么做这样的事情来获取值:

elem.checked

or要么

$(elem).prop('checked')

Automated自动化

$(document).ready(function()
{
    $('#isAgeSelected').change(function()
    {
        alert( 'value =' + $('#chkSelect').attr('checked') );
    });
});

HTML HTML

<b> <input type="isAgeSelected" id="chkSelect" /> Age Check </b>

<br/><br/>

<input type="button" id="btnCheck" value="check" />

jQuery查询

$(document).ready(function()
{
    $('#btnCheck').click(function()
    {
        var isChecked = $('#isAgeSelected').attr('checked');

        if (isChecked == 'checked')
            alert('check-box is checked');
        else
            alert('check-box is not checked');
    })
});

Ajax阿贾克斯

function check()
{
    if (isAgeSelected())
        alert('check-box is checked');
    else
        alert('check-box is not checked');
}

function isAgeSelected()
{
    return ($get("isAgeSelected").checked == true);
}

This is the minimal amount of code I think I needed to do something like this effectively.这是我认为有效地执行此类操作所需的最少代码量。 I found this method to be useful;我发现这个方法很有用; it returns an array of the check boxes that are checked and then you can use their value (this solution uses jQuery):它返回选中的复选框数组,然后您可以使用它们的值(此解决方案使用 jQuery):

// This is how you get them
var output = "";
var checkedBoxes = $("DivCheckBoxesAreIn").children("input:checked");
if(checkedBoxes.length <= 0) {
    alert('Please select check boxes');
    return false;
};

// And this is how you use them:
checkedBoxes.each(function() {
    output +=  this.value + ", ";
};

Printing "output" will give you a comma-separated list of your values.打印“输出”将为您提供一个以逗号分隔的值列表。

 $(document).on("click","#isAgeSelected",function(){ if($(this).prop("checked") == true){ $("#txtAge").show(); } else if($(this).prop("checked") == false){ $("#txtAge").hide(); } });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" id="isAgeSelected"/> <div id="txtAge" style="display:none"> <input type="text" name="age" placeholder="Please enter age" /> </div>

I was having the same problem and none of the posted solutions seemed to work and then I found out that it's because ASP.NET renders the CheckBox control as a SPAN with INPUT inside, so the CheckBox ID is actually an ID of a SPAN, not an INPUT, so you should use:我遇到了同样的问题,但发布的解决方案似乎都没有用,然后我发现这是因为 ASP.NET 将 CheckBox 控件呈现为内部带有 INPUT 的 SPAN,因此 CheckBox ID 实际上是 SPAN 的 ID,而不是一个输入,所以你应该使用:

$('#isAgeSelected input')

rather than而不是

$('#isAgeSelected')

and then all methods listed above should work.然后上面列出的所有方法都应该起作用。

Simply use it like below只需像下面这样使用它

 $('#isAgeSelected').change(function() {
     if ($(this).is(":checked")) { // or if($("#isAgeSelected").attr('checked') == true){
         $('#txtAge').show();
     } else {
         $('#txtAge').hide();
     }
 });

Using pure JavaScript :使用纯JavaScript

let checkbox = document.getElementById('checkboxID');

if(checkbox.checked) {
  alert('is checked');
} else {
  alert('not checked yet');
}

Here's an example that includes initialising the show/hide to match the state of the checkbox when the page loads ;这是一个示例,其中包括初始化显示/隐藏以匹配页面加载时复选框的状态; taking account of the fact that firefox remembers the state of checkboxes when you refresh the page, but won't remember the state of the shown/hidden elements.考虑到当您刷新页面时 Firefox 会记住复选框的状态,但不会记住显示/隐藏元素的状态。

$(function() {
    // initialise visibility when page is loaded
    $('tr.invoiceItemRow').toggle($('#showInvoiceItems').attr('checked'));
    // attach click handler to checkbox
    $('#showInvoiceItems').click(function(){ $('tr.invoiceItemRow').toggle(this.checked);})
});

(with help from other answers on this question) (在这个问题的其他答案的帮助下)

This was my workaround:这是我的解决方法:

$('#vcGoButton').click(function () {
    var buttonStatus = $('#vcChangeLocation').prop('checked');
    console.log("Status is " + buttonStatus);
    if (buttonStatus) {
        var address = $('#vcNewLocation').val();
        var cabNumber = $('#vcVehicleNumber').val();
        $.get('postCabLocation.php',
              {address: address, cabNumber: cabNumber},
              function(data) {
                  console.log("Changed vehicle " + cabNumber + " location to " + address );
              });
    }
    else {
        console.log("VC go button clicked, but no location action");
    }
});

Use:采用:

$(this).toggle($("input:checkbox", $(this))[0].checked);

When you are selecting out of context, remember you need the [0] to access the checkbox.当您在上下文之外进行选择时,请记住您需要 [0] 才能访问该复选框。

Setter:二传手:

$("#chkmyElement")[0].checked = true;

Getter:吸气剂:

if($("#chkmyElement")[0].checked) {
   alert("enabled");
} else {
   alert("disabled");
}

I would actually prefere the change event.我实际上更喜欢change事件。

$('#isAgeSelected').change(function() {
    $("#txtAge").toggle(this.checked);
});

Demo Fiddle演示小提琴

A selector returns multiple objects, and it must take the first item in the array:选择器返回多个对象,它必须取数组中的第一项:

// Collection
var chckremember = $("#chckremember");


// Result boolen
var ischecked=chckremember[0].checked;

Try this,试试这个,

$('#isAgeSelected').click(function() {
    if(this.checked){
        $("#txtAge").show();
    } else{
        $("#txtAge").hide();
    } 
});

I'm using jQuery 1.11.1 and I had troubles with setting and reading checkbox value as well.我使用的是 jQuery 1.11.1,我在设置和读取复选框值时也遇到了麻烦。

I finally solved it by these two functions:我终于通过这两个功能解决了它:

function setCheckboxValue(checkBoxId, checked) {
    if (checkBoxId && (checked === true || checked === false)) {
        var elem = $('#' + checkBoxId);
        if (checked === true) {
            elem.attr('checked', 'checked');
        } else {
            elem.removeAttr('checked');
        }
    }
}

function isChecked(checkBoxId) {
    return $('#' + checkBoxId).attr('checked') != null;
}

It might looks a little bit dirty but it solves all the wired issue I had among different types of browsers.它可能看起来有点脏,但它解决了我在不同类型的浏览器中遇到的所有有线问题。

You Can Try This code:你可以试试这个代码:

$('#isAgeSelected').click(function(){
   console.log(this.checked);
   if(this.checked == true) {
        $("#txtAge").show();
    } else {
       $("#txtAge").hide();
   }
});
if( undefined == $('#isAgeSelected').attr('checked') ) {
    $("#txtAge").hide();
} else {
    $("#txtAge").show();
}

What about this solution?这个解决方案怎么样?

$("#txtAge")[
    $("#isAgeSelected").is(':checked') ?
    'show' :
    'hide'
]();

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.我需要检查复选框的选中属性,并使用 jQuery 根据选中的属性执行操作。

EX -前任 -

1) Run On load to get checkbox value if the age checkbox is checked, then I need to show a text box to enter age, else hide the text box. 1)如果选中年龄复选框,则在加载时运行以获取复选框值,然后我需要显示一个文本框来输入年龄,否则隐藏文本框。

2) if the age checkbox is checked, then I need to show a text box to enter age, else hide the text box using click event of checkbox. 2)如果选中了年龄复选框,那么我需要显示一个文本框来输入年龄,否则使用复选框的单击事件隐藏文本框。

so code not returns false by default:所以代码默认不返回false:

Try the following:尝试以下操作:

<html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        </head>
        <body>
            <h1>Jquery Demo</h1>
            <input type="checkbox" name="isAge" checked id="isAge"> isAge <br/>
            <div id="Age" style="display:none">
              <label>Enter your age</label>
              <input type="number" name="age">
            </div>
            <script type="text/javascript">
            if(document.getElementById('isAge').checked) {
                $('#Age').show();
            } else {
                $('#Age').hide();
            }   
            $('#isAge').click(function() {
                if(document.getElementById('isAge').checked) {
                    $('#Age').show();
                } else {
                    $('#Age').hide();
                }
            }); 
            </script>
        </body>
    </html>

Here is a modified version: https://jsfiddle.net/sedhal/0hygLtrz/7/这是修改后的版本: https ://jsfiddle.net/sedhal/0hygLtrz/7/

Hi you can use plain Javascript , like so:您好,您可以使用纯Javascript ,如下所示:

 document.getElementById('checkboxOption').addEventListener('click', event => console.log(event.target.checked) );
 <label><input type="checkbox" id="checkboxOption">Check Option</label>

In case you need to know if a checkbox is checked in pure javascript you should use this code.如果您需要知道是否在纯javascript中选中了复选框,您应该使用此代码。

let checkbox =document.getElementById('myCheckboxId');
if(checkbox.checked) {
    alert("element is checked");
} else {
    alert("element is  ot checked");
}

In pure js checkbox state is easier to read在纯 js 中,复选框状态更易于阅读

isAgeSelected.checked

 function check() { txtAge.style.display= isAgeSelected.checked? 'block':'none'; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Age <input type="checkbox" id="isAgeSelected"/> <button onclick="check()">Check</button> <div id="txtAge" style="display:none"> Age is selected </div>

if( undefined == $('#isAgeSelected').attr('checked') ) {
    $("#txtAge").hide();
} else {
    $("#txtAge").show();
}

For older versions of jQuery, I had to use following,对于旧版本的 jQuery,我不得不使用以下内容,

$('#change_plan').live('click', function() {
     var checked = $('#change_plan').attr('checked');
     if(checked) {
          //Code       
     }
     else {
          //Code       
     }
});
$(document).on('change', '#isAgeSelected', function() {

    if($(this).is(":checked")){

       $('#txtAge').hide();
    }
    else
    {
        $('#txtAge').hide();
    }
});

In case if you need to use CSS class as jQuery selector you can do following:如果您需要使用 CSS 类作为 jQuery 选择器,您可以执行以下操作:

$(document).ready(function () {
        $('.myOptionCheckbox').change(function () {            
            if ($(this).prop('checked') == true) {
                console.log("checked");           
            }
            else {
                console.log("unchecked");                
            }
        });
    });

It works fine for checkboxes and radioboxes as well.它也适用于checkboxesradioboxes

This function is alternative and stable:这个功能是可选的和稳定的:

$('#isAgeSelected').context.checked
(return True/False)

Example:例子:

if($('#isAgeSelected').context.checked){ //if Checkbox is checked then bla bla..
    /*.....*/
}else{
    /*.....*/
}
$('#chk').change(function() { 
    (this.checked)? alert('true') : alert('false');
});



($('#chk')[0].checked)? alert('true') : alert('false');
if($('#isAgeSelected').prop('checked')) {
    // do your action 
}

You could try the followings in both ways:您可以通过两种方式尝试以下操作:

var getVal=$('#isAgeSelected').is(":checked"); // jQuery

var getVal=document.getElementById("isAgeSelected").checked //JavaScript

if (getVal==true) {
 $("#txtAge").show();  // checked
} else {
 $("#txtAge").hide();  // unchecked
}

$("#isAgeSelected").prop('checked', true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM